"use client"
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Typography,
  CircularProgress,
  Alert,
  TextField,
  Box,
} from "@mui/material"
import { useState } from "react"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faX } from "@fortawesome/free-solid-svg-icons"
import { IDocumentRequest, RequestStatus } from "@/shared/types/document-request"
import { useDocumentRequestStore } from "@/shared/api/stores/admin-service/requestDocsStore"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

interface Props {
  open: boolean
  onClose: () => void
  request: IDocumentRequest | null
  onRequestUpdated?: (updatedRequest: IDocumentRequest) => void
}

export default function RejectConfirmationDialog({ 
  open, 
  onClose, 
  request, 
  onRequestUpdated 
}: Props) {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [rejectionReason, setRejectionReason] = useState("")

  const { rejectRequest } = useDocumentRequestStore()

  const handleReject = async () => {
    if (!request) return

    setLoading(true)
    setError(null)

    try {
      await rejectRequest(request.codeReq)
      const updatedRequest: IDocumentRequest = {
        ...request,
        statut: RequestStatus.REFUSEE,
        processingDate: new Date().toISOString(),
        observation: rejectionReason || request.observation
      }
      
      if (onRequestUpdated) {
        onRequestUpdated(updatedRequest)
      }
      
      handleClose()
    } catch (error: any) {
      setError(error.message || "Erreur lors du rejet")
    } finally {
      setLoading(false)
    }
  }

  const handleClose = () => {
    setRejectionReason("")
    setError(null)
    setLoading(false)
    onClose()
  }

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
      <DialogTitle>
        Rejeter la demande
      </DialogTitle>

      <DialogContent>
        <ConditionalComponent isValid={!!error}>
          <Alert severity="error" sx={{ mb: 2 }}>
            {error}
          </Alert>
        </ConditionalComponent>
        
        <ConditionalComponent isValid={!!request}>
          <Box sx={{ mb: 3 }}>
            <Typography variant="h6" gutterBottom>
              Demande: {request?.codeReq}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              Demandeur: {request?.userName}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              Type: {getRequestTypeLabel(request?.title)}
            </Typography>
          </Box>
        </ConditionalComponent>

        <Typography variant="body1" sx={{ mb: 2 }}>
          Êtes-vous sûr de vouloir rejeter cette demande de document ?
        </Typography>

        <TextField
          fullWidth
          multiline
          rows={3}
          label="Motif du rejet (optionnel)"
          value={rejectionReason}
          onChange={(e) => setRejectionReason(e.target.value)}
          placeholder="Expliquez pourquoi cette demande est rejetée..."
          sx={{ mb: 2 }}
        />
      </DialogContent>

      <DialogActions>
        <Button onClick={handleClose} disabled={loading}>
          Annuler
        </Button>

        <Button
          onClick={handleReject}
          variant="contained"
          color="error"
          disabled={loading}
          startIcon={loading ? <CircularProgress size={16} /> : <FontAwesomeIcon icon={faX} />}
        >
          {loading ? "Rejet..." : "Rejeter la demande"}
        </Button>
      </DialogActions>
    </Dialog>
  )
}

const getRequestTypeLabel = (type: any): string => {
  const requestTypeMap = {
    PERSONAL_JUSTIFICATION: "Justificatif personnel",
    OFFICIAL_DOCUMENT: "Document officiel",
    ADMINISTRATIVE_FILE: "Fichier administratif",
    EMPLOYMENT_CONTRACT: "Contrat de travail",
    OTHER: "Autre",
  }
  return requestTypeMap[type as keyof typeof requestTypeMap] || type
}