"use client"

import React, { useState, useCallback } from "react"
import { IconButton, Menu, type MenuProps } from "@mui/material"
import MenuItem from "@mui/material/MenuItem"
import { alpha, styled } from "@mui/system"
import { faFileExport } from "@fortawesome/free-solid-svg-icons"
import { 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 ExportOption {
  label: string
  action: () => void
}

interface BackendExportButtonProps {
  tooltipTitle: string
  isTableExport?: boolean
  exportOptions: ExportOption[]
}

function BackendExportButton({
  tooltipTitle,
  isTableExport,
  exportOptions,
}: BackendExportButtonProps) {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
  const open = Boolean(anchorEl)

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

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

  const handleOptionClick = useCallback(
    async (action: () => void) => {
      await action();
      handleClose();
    },
    [handleClose],
  );

  return (
    <>
      <CustomTooltip title={tooltipTitle} arrow>
        <IconButton onClick={handleClick} sx={isTableExport ? WhiteIconButtonStyle : {}}>
          <FontAwesome icon={faFileExport} width={isTableExport ? 18 : 16} />
        </IconButton>
      </CustomTooltip>
      <StyledMenu
        id="backend-export-menu"
        MenuListProps={{
          "aria-labelledby": "backend-export-button",
        }}
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
      >
        {exportOptions.map((option, index) => (
          <MenuItem key={index} onClick={() => handleOptionClick(option.action)} disableRipple>
            {option.label}
          </MenuItem>
        ))}
      </StyledMenu>
    </>
  )
}

export default React.memo(BackendExportButton)