"use client"

import { useState, useCallback } from "react"
import {
  CircularProgress,
  Typography,
  Box,
  Dialog,
  DialogContent,
  DialogTitle,
  IconButton,
  Divider,
  Button,
  useTheme,
  Paper,
  Grid,
  Snackbar,
  Alert,
} from "@mui/material"
import ExportTemplate from "./export-template"
import Upload from "../upload/upload"
import {
  faFileExport,
  faFileUpload,
  faTimes,
  faCloudUploadAlt,
  faArrowLeft,
  faTrashAlt,
} from "@fortawesome/free-solid-svg-icons"
import FontAwesome from "../fontawesome"
import { TypeImport } from "@/shared/types/common"

interface MassUploadFileProps {
  open: boolean
  onClose: () => void
  type?: TypeImport
  withData?: boolean
  skipExport?: boolean
  customBackendExport?: () => void
  customUpload?: (file: File) => void
  isExportingTemplate?: boolean
  allowedExtensions?: string[]
}

export default function MassUploadFile({ open, onClose, type = TypeImport.CIRCUIT, withData,skipExport = false, customBackendExport, customUpload, isExportingTemplate, allowedExtensions }: MassUploadFileProps) {
  const TYPE_LABELS: Record<TypeImport, string> = {
    [TypeImport.CIRCUIT]: "Circuits",
    [TypeImport.VACANCE]: "Vacances",
    [TypeImport.PASSENGER]: "Usagers",
    [TypeImport.FUEL]: "Fournisseur",
    [TypeImport.GEOLOC]: "Géolocalisation",
    [TypeImport.FuelFee]: "Frais Carburents",
    [TypeImport.ESTABLISHMENT]: "Établissements",

  }

  const getTypeLabel = () => TYPE_LABELS[type] || "Inconnu"
  const [files, setFiles] = useState<File[]>([])
  const [loading, setLoading] = useState(false)
  const [currentFile, setCurrentFile] = useState<File | null>(null)
  const [isExporting, setIsExporting] = useState(!skipExport)
  const [openSnackbar, setOpenSnackbar] = useState(false)
  const theme = useTheme()

  const uploadAccept = (() => {
    if (!allowedExtensions || allowedExtensions.length === 0) {
      return undefined;
    }
    const mapped: Record<string, string[]> = {}
    if (allowedExtensions.includes('.xlsx')) {
      mapped["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"] = [".xlsx"]
    }
    if (allowedExtensions.includes('.xls')) {
      mapped["application/vnd.ms-excel"] = [".xls"]
    }
    return mapped
  })()

  const handleDrop = useCallback((acceptedFiles: File[]) => {
    if (acceptedFiles.length > 0) {
      const file = acceptedFiles[0]
      setFiles([file])
      setCurrentFile(file)
    }
  }, [])

  const handleUpload = async () => {
    setLoading(true)
    try {
      const file = files[0]
      if (file) {
        setCurrentFile(file)
        customUpload?.(file)
        setOpenSnackbar(true)
        setTimeout(() => {
          onClose()
        }, 1000)
      }
    } catch (error) {
      console.error("Failed to upload file:", error)
    } finally {
      setLoading(false)
      setCurrentFile(null)
      setFiles([])
    }
  }

  const handleRemoveFile = () => {
    setFiles([])
    setCurrentFile(null)
  }

  const closeDialog = () => {
    onClose()
    setIsExporting(true)
  }

  const handleExportComplete = () => setIsExporting(false)
  const handleSkipExport = () => setIsExporting(false)

  const getExportTitle = () => {
    return withData
      ? `Exporter les données ${getTypeLabel()} actuelles`
      : `Exporter le Template ${getTypeLabel()}`
  }

  return (
    <div>
      <Dialog
        open={open}
        onClose={closeDialog}
        fullWidth
        maxWidth="sm"
        PaperProps={{
          sx: {
            borderRadius: 4,
            overflow: "hidden",
          },
        }}
      >
        <DialogTitle
          sx={{
            backgroundColor: theme.palette.primary.main,
            color: "white",
            fontWeight: "600",
            padding: "16px 24px",
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            borderBottom: `1px solid ${theme.palette.divider}`,
          }}
        >
          <Box sx={{ display: "flex", alignItems: "center" }}>
            <FontAwesome
              icon={isExporting ? faFileExport : faFileUpload}
              sx={{ color: "white", marginRight: "12px", width: { xs: 32, lg: 32 }, height: { xs: 32, lg: 32 } }}
            />
            <Typography variant="h6" sx={{ fontSize: "1.25rem", fontWeight: "bold", color: "white" }}>
              {isExporting ? getExportTitle() : `Importer un fichier ${getTypeLabel()}`}
            </Typography>
          </Box>
          <IconButton edge="end" color="inherit" onClick={closeDialog} aria-label="close" sx={{ color: "white" }}>
            <FontAwesome icon={faTimes} />
          </IconButton>
        </DialogTitle>

        <Divider />

        <DialogContent
          sx={{
            backgroundColor: "#fafafa",
            padding: "24px",
            display: "flex",
            flexDirection: "column",
            gap: "16px",
          }}
        >
          {isExporting ? (
            <ExportTemplate onExport={handleExportComplete} onSkip={handleSkipExport} type={type} withData={withData} customBackendExport={customBackendExport} isExporting={isExportingTemplate} />
          ) : (
            <>
              {loading ? (
                <Box
                  sx={{
                    display: "flex",
                    flexDirection: "column",
                    justifyContent: "center",
                    alignItems: "center",
                    height: "200px",
                  }}
                >
                  <CircularProgress size={48} sx={{ color: theme.palette.primary.main }} />
                  <Typography variant="body1" sx={{ mt: 2, color: theme.palette.grey[900] }}>
                    Importation en cours...
                  </Typography>
                  {currentFile ? (
                    <Typography
                      variant="body2"
                      sx={{ mt: 1, color: theme.palette.grey[900] }}
                    >{`Fichier : ${currentFile.name}`}</Typography>
                  ) : null}
                </Box>
              ) : (
                <Paper
                  sx={{
                    padding: "20px",
                    borderRadius: "8px",
                    boxShadow: 3,
                    backgroundColor: theme.palette.background.paper,
                  }}
                >
                  <Upload
                    multiple
                    files={files}
                    onDrop={handleDrop}
                    onRemove={handleRemoveFile}
                  accept={uploadAccept}
                  allowedExtensions={allowedExtensions}
                  />
                </Paper>
              )}

              <Box sx={{ mt: 2 }}>
                <Grid container spacing={2}>
                  <Grid item xs={12} md={6}>
                    <Button
                      variant="contained"
                      startIcon={<FontAwesome icon={faCloudUploadAlt} />}
                      onClick={handleUpload}
                      disabled={loading}
                      sx={{
                        backgroundColor: theme.palette.primary.main,
                        "&:hover": {
                          backgroundColor: theme.palette.primary.dark,
                        },
                        width: "100%",
                        padding: "12px 16px",
                        borderRadius: "8px",
                        boxShadow: 2,
                      }}
                    >
                      Importer
                    </Button>
                  </Grid>

                  {!files.length && !loading ? (
                    <Grid item xs={12} md={6}>
                      <Button
                        variant="outlined"
                        onClick={() => {
                          setIsExporting(true)
                        }}
                        startIcon={<FontAwesome icon={faArrowLeft} />}
                        sx={{
                          width: "100%",
                          padding: "12px 16px",
                          borderRadius: "8px",
                          color: theme.palette.primary.main,
                          borderColor: theme.palette.primary.main,
                          "&:hover": {
                            borderColor: theme.palette.primary.dark,
                            color: theme.palette.primary.dark,
                          },
                        }}
                      >
                        Retour
                      </Button>
                    </Grid>
                  ) : null}

                  {!!files.length && !loading ? (
                    <Grid item xs={12} md={6}>
                      <Button
                        variant="outlined"
                        color="error"
                        onClick={handleRemoveFile}
                        disabled={loading}
                        startIcon={<FontAwesome icon={faTrashAlt} />}
                        sx={{
                          width: "100%",
                          padding: "12px 16px",
                          borderRadius: "8px",
                          color: theme.palette.error.main,
                          borderColor: theme.palette.error.main,
                          "&:hover": {
                            borderColor: theme.palette.error.dark,
                            color: theme.palette.error.dark,
                          },
                        }}
                      >
                        Retirer
                      </Button>
                    </Grid>
                  ) : null}
                </Grid>
              </Box>
            </>
          )}
        </DialogContent>
      </Dialog>
      <Snackbar open={openSnackbar} autoHideDuration={2000} onClose={() => setOpenSnackbar(false)}>
        <Alert onClose={() => setOpenSnackbar(false)} severity="success" sx={{ width: "100%" }}>
          {`Vos données ${getTypeLabel()} ont été bien téléchargées !`}
        </Alert>
      </Snackbar>
    </div>
  )
}

