"use client"

import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Typography,
  Box,
  Stepper,
  Step,
  StepLabel,
  CircularProgress,
  Alert,
  Input,
} from "@mui/material"
import { useState } from "react"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faCheck, faUpload } from "@fortawesome/free-solid-svg-icons"
import { RequestStatus, type IDocumentRequest } from "@/shared/types/document-request"
import { useDocumentRequestStore } from "@/shared/api/stores/admin-service/requestDocsStore"
import { AddDocumentRequest } from "@/shared/types/document"
import { useDocumentStore } from "@/shared/api/stores/document-service/docsStore"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"


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

const steps = ["Approuver la demande", "Attacher le document"]

export default function ApproveUploadDialog({ open, onClose, request, actionType, onRequestUpdated }: Props) {
  const [activeStep, setActiveStep] = useState(0)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [uploadLoading, setUploadLoading] = useState(false)

  const { approveRequest } = useDocumentRequestStore()
  const upload = useDocumentStore((s) => s.upload);

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

    setLoading(true)
    setError(null)

    try {
      await approveRequest(request.codeReq)
      setActiveStep(1) // Move to next step
    } catch (error: any) {
      setError(error.message || "Erreur lors de l'approbation")
    } finally {
      setLoading(false)
    }
  }

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      setSelectedFile(file)
    }
  }

  const handleUploadAndSend = async () => {
    if (!request || !selectedFile) return

    setUploadLoading(true)
    setError(null)

    try {
      const documentData: AddDocumentRequest = {
        name: selectedFile.name,
        documentType: request.type,
        ownerUuid: request.userUuid?.toString(),
        ownerId: request.userId,
        folderId: null,
      }

      await upload(selectedFile, documentData)
      const updatedRequest: IDocumentRequest = {
      ...request,
      statut: RequestStatus.VALIDEE,
      processingDate: new Date().toISOString()
    }
    
    if (onRequestUpdated) {
      onRequestUpdated(updatedRequest)
    }
      onClose()
      handleReset()
    } catch (error: any) {
      setError(error.message || "Erreur lors de l'upload")
    } finally {
      setUploadLoading(false)
    }
  }

  const handleReset = () => {
    setActiveStep(0)
    setLoading(false)
    setError(null)
    setSelectedFile(null)
    setUploadLoading(false)
  }

  const handleClose = () => {
    handleReset()
    onClose()
  }

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="md" fullWidth>
      <DialogTitle>
        {actionType === "approve" ? "Approuver la demande" : "Générer un document"}
      </DialogTitle>

      <DialogContent>
        <Box sx={{ mb: 3 }}>
          <Stepper activeStep={activeStep} alternativeLabel>
            {steps.map((label) => (
              <Step key={label}>
                <StepLabel>{label}</StepLabel>
              </Step>
            ))}
          </Stepper>
        </Box>
        <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: {request?.type}
            </Typography>
          </Box>
        </ConditionalComponent>
        
        <ConditionalComponent isValid={activeStep === 0}>
          <Box>
            <Typography variant="body1" sx={{ mb: 2 }}>
              Cliquez sur &quot;Approuver&quot; pour valider cette demande de document.
            </Typography>
          </Box>
        </ConditionalComponent>
        <ConditionalComponent isValid={activeStep === 1}>
          <Box>
            <Typography variant="body1" sx={{ mb: 2 }}>
              Sélectionnez le document à envoyer au demandeur:
            </Typography>
            
            <Box sx={{ mb: 2 }}>
              <Input
                type="file"
                onChange={handleFileSelect}
                inputProps={{ accept: ".pdf,.doc,.docx,.jpg,.jpeg,.png" }}
              />
            </Box>
            <ConditionalComponent isValid={!!selectedFile}>
              <Typography variant="body2" color="text.secondary">
                Fichier sélectionné: {selectedFile?.name}
              </Typography>
            </ConditionalComponent>
          </Box>
        </ConditionalComponent>
      </DialogContent>

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

        <ConditionalComponent isValid={activeStep === 0}>
          <Button
            onClick={handleApprove}
            variant="contained"
            disabled={loading}
            startIcon={loading ? <CircularProgress size={16} /> : <FontAwesomeIcon icon={faCheck} />}
          >
            {loading ? "Approbation..." : "Approuver"}
          </Button>
        </ConditionalComponent>
        <ConditionalComponent isValid={activeStep === 1}>
          <Button
            onClick={handleUploadAndSend}
            variant="contained"
            disabled={!selectedFile || uploadLoading}
            startIcon={uploadLoading ? <CircularProgress size={16} /> : <FontAwesomeIcon icon={faUpload} />}
          >
            {uploadLoading ? "Envoi..." : `Envoyer à ${request?.userName}`}
          </Button>
        </ConditionalComponent>
      </DialogActions>
    </Dialog>
  )
}