"use client"

import { useState } from "react"
import {
  DialogContent, DialogActions, Button, Box, Typography,
  FormControl, InputLabel, Select, MenuItem
} from "@mui/material"
import { CloudUpload as CloudUploadIcon } from "@mui/icons-material"
import { StyledDialog, StyledDialogTitle } from "@/shared/sections/rh/styles"
import { StyledTextField } from "@/shared/theme/css"
import { AddButton } from "@/shared/components/table/styles"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { useDocumentStore } from "@/shared/api/stores/document-service/docsStore"
import { ContentTypeEnum, DocumentDTO, DocumentTypeEnum } from "@/shared/types/document"
import type { AddDocumentRequest, FolderDTO } from "@/shared/types/document"
import { CircularProgress } from "@mui/material"

interface UploadFileDialogProps {
  open: boolean
  onClose: () => void
  onUpload: (document: DocumentDTO) => void,
  folder: FolderDTO | null
}

export default function UploadFileDialog({ open, onClose, onUpload, folder }: UploadFileDialogProps) {
  const [fileName, setFileName] = useState("")
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [documentType, setDocumentType] = useState<DocumentTypeEnum>(DocumentTypeEnum.ID_CARD)
  const [error, setError] = useState("")
  const [isUploading, setIsUploading] = useState(false)

  const upload = useDocumentStore((s) => s.upload)


  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      setSelectedFile(file)
      if (!fileName) setFileName(file.name.split(".").slice(0, -1).join("."))
    }
  }

  function getFileExtension(filename : string) {
  const match = filename.match(/\.[^/.]+$/);
  return match ? match[0] : null;
}
  const handleSubmit = async () => {
    if (!selectedFile) return setError("Veuillez sélectionner un fichier")
    if (!fileName.trim()) return setError("Veuillez entrer un nom de fichier")

    const addDocRequest: AddDocumentRequest = {
      name: fileName + getFileExtension(selectedFile.name),
      documentType,
      ownerUuid: localStorage.getItem("userUuid") as string,
      ownerId: Number(localStorage.getItem("userId")),
      folderId: folder ? folder.id : null,
    }
    setIsUploading(true) // Start loading
    setError("")

    try {
      const document = await upload(selectedFile, addDocRequest)
      onUpload(document)
      resetForm()
      onClose();
    } catch (err) {
      console.error("Upload failed", err)
      setError("Échec de l'importation")
    } finally {
      setIsUploading(false) // Stop loading
    }
  }

  const resetForm = () => {
    setFileName("")
    setSelectedFile(null)
    setDocumentType(DocumentTypeEnum.ID_CARD)
    setError("")
    setIsUploading(false)
  }

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

  return (
    <StyledDialog open={open} onClose={isUploading ? undefined : handleClose} maxWidth="sm" fullWidth>
      <ConditionalComponent isValid={isUploading}>
        <Box
          sx={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: 'rgba(255, 255, 255, 0.8)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            zIndex: 1000,
            borderRadius: 2,
          }}
        >
          <Box sx={{ textAlign: 'center' }}>
            <CircularProgress size={40} />
            <Typography variant="body2" sx={{ mt: 2 }}>
              Importation en cours...
            </Typography>
          </Box>
        </Box>
      </ConditionalComponent>
      <StyledDialogTitle>Importer un fichier</StyledDialogTitle>
      <DialogContent>
        <Box sx={{ mb: 2 }}>
          <StyledTextField
            label="Nom du fichier"
            fullWidth
            value={fileName}
            onChange={(e) => setFileName(e.target.value)}
            margin="normal"
            error={!!error && !fileName}
            helperText={error && !fileName ? error : ""}
          />
        </Box>
        <Box sx={{ mb: 2 }}>
          <FormControl fullWidth margin="normal">
            <InputLabel>Type de document</InputLabel>
            <Select
              value={documentType}
              label="Type de document"
              onChange={(e) => setDocumentType(e.target.value as DocumentTypeEnum)}
            >
              <MenuItem value="WORK_CERTIFICATE">Certificat de travail</MenuItem>
              <MenuItem value="PRESENCE_CERTIFICATE">Certificat de présence</MenuItem>
              <MenuItem value="ID_CARD">Carte d&apos;identité</MenuItem>
              <MenuItem value="DRIVER_LICENCE">Permis de conduire</MenuItem>
            </Select>
          </FormControl>
        </Box>

        <Box component="label" sx={{
          display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
          gap: 2, border: "2px dashed", borderColor: "divider", borderRadius: 2,
          p: 3, textAlign: "center", bgcolor: "background.paper", cursor: "pointer",
          "&:hover": { borderColor: "primary.main" }
        }}>
          <input type="file" hidden onChange={handleFileChange} />
          <CloudUploadIcon color="primary" sx={{ fontSize: 48 }} />
          <Typography variant="body1" gutterBottom>
            Cliquez ou glissez-déposez un fichier ici
          </Typography>
          <ConditionalComponent isValid={!!selectedFile}>
            <Typography variant="body2" color="text.secondary">
              Fichier sélectionné: {selectedFile?.name}
            </Typography>
          </ConditionalComponent>
          <ConditionalComponent isValid={!!error && !selectedFile}>
            <Typography variant="body2" color="error">
              {error}
            </Typography>
          </ConditionalComponent>
        </Box>
      </DialogContent>
      <DialogActions>
        <AddButton variant="outlined" onClick={handleClose}>Annuler</AddButton>
        <Button variant="contained" onClick={handleSubmit} disabled={!selectedFile || !fileName.trim()}>
          Importer
        </Button>
      </DialogActions>
    </StyledDialog>
  )
}
