"use client"

import React, { useState, useCallback, useRef } from "react"
import { IconButton, Menu, type MenuProps, MenuItem } from "@mui/material"
import { alpha, styled } from "@mui/system"
import { faFileImport } from "@fortawesome/free-solid-svg-icons"
import { iconButtonStyles, WhiteIconButtonStyle } from "@/shared/theme/css"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import FontAwesome from "@/shared/components/fontawesome"

const StyledMenu = styled((props: MenuProps) => (
  <Menu
    elevation={0}
    anchorOrigin={{
      vertical: "bottom",
      horizontal: "right",
    }}
    transformOrigin={{
      vertical: "top",
      horizontal: "right",
    }}
    {...props}
  />
))(({ theme }) => ({
  "& .MuiPaper-root": {
    borderRadius: 12,
    marginTop: 4,
    backgroundColor: "white",
    boxShadow: "0px 4px 20px rgba(0, 0, 0, 0.1)",
    "& .MuiMenu-list": {
      padding: "8px 0",
    },
    "& .MuiMenuItem-root": {
      fontSize: "0.8rem",
      "&:hover": {
        backgroundColor: alpha(theme.palette.primary.main, 0.1),
        color: theme.palette.primary.main,
      },
    },
  },
}))

interface ImportOption {
  label: string
  accept: string
  action: (file: File) => void
}

interface ImportButtonProps {
  tooltipTitle: string
  isTableImport?: boolean
  onImportSuccess?: () => void
  type: string
}

function ImportButton({ tooltipTitle, isTableImport = false, onImportSuccess, type }: ImportButtonProps) {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [currentImportType, setCurrentImportType] = useState<string>("")
  const open = Boolean(anchorEl)

  const handleImportCSV = useCallback(
    (file: File) => {
      if (onImportSuccess) {
        onImportSuccess()
      }
    },
    [onImportSuccess],
  )

  const handleImportExcel = useCallback(
    (file: File) => {
      if (onImportSuccess) {
        onImportSuccess()
      }
    },
    [onImportSuccess],
  )

  const handleImportPDF = useCallback(
    (file: File) => {
      if (onImportSuccess) {
        onImportSuccess()
      }
    },
    [onImportSuccess],
  )

  const importOptions: ImportOption[] = React.useMemo(
    () => [
      { label: "Importer un fichier CSV", accept: ".csv", action: handleImportCSV },
      { label: "Importer un fichier Excel", accept: ".xlsx,.xls", action: handleImportExcel },
      { label: "Importer un fichier PDF", accept: ".pdf", action: handleImportPDF },
    ],
    [handleImportCSV, handleImportExcel, handleImportPDF],
  )

  const handleClick = useCallback((event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget)
  }, [])

  const handleClose = useCallback(() => {
    setAnchorEl(null)
  }, [])

  const handleOptionClick = useCallback(
    (accept: string, action: (file: File) => void) => {
      setCurrentImportType(accept)
      // We need to reset the file input value to allow selecting the same file again
      if (fileInputRef.current) {
        fileInputRef.current.value = ""
        fileInputRef.current.accept = accept
        fileInputRef.current.click()
      }
      handleClose()
    },
    [handleClose],
  )

  const handleFileChange = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      const files = event.target.files
      if (files && files.length > 0) {
        const file = files[0]
        const fileExt = `.${file.name.split(".").pop() || ""}`
        const option = importOptions.find((opt) => opt.accept.includes(fileExt))
        if (option) {
          option.action(file)
        }
      }
    },
    [importOptions],
  )

  return (
    <>
      <input
        type="file"
        ref={fileInputRef}
        style={{ display: "none" }}
        onChange={handleFileChange}
        accept={currentImportType}
      />
      <CustomTooltip title={tooltipTitle} arrow>
        <IconButton onClick={handleClick} sx={isTableImport ? WhiteIconButtonStyle : iconButtonStyles}>
          <FontAwesome icon={faFileImport} width={isTableImport ? 18 : 16} />
        </IconButton>
      </CustomTooltip>
      <StyledMenu
        id="import-menu"
        MenuListProps={{
          "aria-labelledby": "import-menu-button",
        }}
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
      >
        {importOptions.map((option, index) => (
          <MenuItem key={index} onClick={() => handleOptionClick(option.accept, option.action)} disableRipple>
            {option.label}
          </MenuItem>
        ))}
      </StyledMenu>
    </>
  )
}

export default React.memo(ImportButton)

