"use client"

import type React from "react"

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 type { DocumentDTO, DocumentTypeEnum, ContentTypeEnum } from "@/shared/types/document"
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"

interface UploadFileDialogProps {
  open: boolean
  onClose: () => void
  onUpload: (document: DocumentDTO) => void
}

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

  const getContentType = (file: File): ContentTypeEnum => {
    const extension = file.name.split(".").pop()?.toLowerCase()
    switch (extension) {
      case "pdf":
        return "PDF" as ContentTypeEnum
      case "jpg":
      case "jpeg":
      case "png":
      case "gif":
        return "IMAGE" as ContentTypeEnum
      case "doc":
      case "docx":
        return "WORD" as ContentTypeEnum
      case "xls":
      case "xlsx":
        return "EXCEL" as ContentTypeEnum
      default:
        return "PDF" as ContentTypeEnum
    }
  }

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

  const handleSubmit = () => {
    if (!selectedFile) {
      setError("Veuillez sélectionner un fichier")
      return
    }

    if (!fileName.trim()) {
      setError("Veuillez entrer un nom de fichier")
      return
    }

    // Create a new document object
    const newDocument: DocumentDTO = {
      id: Date.now(),
      name: fileName,
      path: `/documents/${selectedFile.name}`,
      size: selectedFile.size,
      contentType: getContentType(selectedFile),
      s3Key: `documents/${Date.now()}-${selectedFile.name}`,
      ownerId: 4, // Using owner ID 4 as specified
      documentType: documentType,
      favorite: false,
    }

    onUpload(newDocument)
    resetForm()
  }

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

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

  return (
    <StyledDialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
      <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
          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",
            },
          }}
          component="label"
        >
          <input type="file" hidden onChange={handleFileChange} />
          <CloudUploadIcon color="primary" sx={{ fontSize: 48 }} />
          <Box>
            <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>
        </Box>
      </DialogContent>
      <DialogActions>
        <AddButton variant="outlined" onClick={handleClose}>
          Annuler
        </AddButton>
        <Button variant="contained" onClick={handleSubmit} disabled={!selectedFile || !fileName.trim()}>
          Importer
        </Button>
      </DialogActions>
    </StyledDialog>
  )
}
