"use client"

import React, { useState, useCallback, useMemo } from "react"
import { IconButton, Menu, type MenuProps, Alert, Snackbar } from "@mui/material"
import MenuItem from "@mui/material/MenuItem"
import { alpha, styled } from "@mui/system"
import { faFileExport } from "@fortawesome/free-solid-svg-icons"
import { TableType, type TableColumn } from "@/shared/types/common"
import { iconButtonStyles, WhiteIconButtonStyle } from "@/shared/theme/css"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import FontAwesome from "@/shared/components/fontawesome"
import { exportToCSV, exportToPDF } from "./export-utils"

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 MenuOption {
  label: string
  action: () => void
}

interface DynamicCustomMenuProps<T> {
  options?: MenuOption[]
  tooltipTitle: string
  type: string
  isTableExport?: boolean
  filteredData: T[]
  tableHead: TableColumn[]
}

function ExportButton<T extends { id: string }>({
  options,
  tooltipTitle,
  isTableExport,
  filteredData,
  type,
  tableHead,
}: DynamicCustomMenuProps<T>) {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
  const open = Boolean(anchorEl)
  const [alertOpen, setAlertOpen] = useState(false)
  const handleAlertClose = useCallback(() => {
    setAlertOpen(false)
  }, [])

  const exportOptions = useMemo(() => {
    if (type === TableType.AttendanceSheet || type === TableType.DriverRoadmap) {
      return [
        { label: "Exporter en PDF", action: () => exportToPDF(filteredData, tableHead, type) }
      ];
    } else {
      return [
        { label: "Exporter en CSV", action: () => exportToCSV(filteredData, tableHead, type) }
      ];
    }
  }, [filteredData, tableHead, type]);


  const menuOptions = options || exportOptions

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

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

  const handleOptionClick = useCallback(
    (action: () => void) => {
      if (filteredData.length === 0) {
        setAlertOpen(true)
      } else {
        action()
      }
      handleClose()
    },
    [filteredData.length, handleClose],
  )
  return (
    <>
      <CustomTooltip title={tooltipTitle} arrow>
        <IconButton onClick={handleClick} sx={isTableExport ? WhiteIconButtonStyle : iconButtonStyles}>
          <FontAwesome icon={faFileExport} width={isTableExport ?  18 : 16} />
        </IconButton>
      </CustomTooltip>
      <StyledMenu
        id="custom-menu"
        MenuListProps={{
          "aria-labelledby": "custom-menu-button",
        }}
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
      >
        {menuOptions.map((option, index) => (
          <MenuItem key={index} onClick={() => handleOptionClick(option.action)} disableRipple>
            {option.label}
          </MenuItem>
        ))}
      </StyledMenu>
      <Snackbar
        open={alertOpen}
        autoHideDuration={6000}
        onClose={handleAlertClose}
        anchorOrigin={{ vertical: "top", horizontal: "center" }}
      >
        <Alert onClose={handleAlertClose} severity="warning" sx={{ width: "100%" }}>
          {"Aucune donnée n'a été sélectionnée pour l'export"}
        </Alert>
      </Snackbar>
    </>
  )
}

export default React.memo(ExportButton)

