"use client";

import { Fragment, useState } from "react";
import type { MouseEvent, ReactNode } from "react";

import Box from "@mui/material/Box";
import ButtonBase from "@mui/material/ButtonBase";
import Divider from "@mui/material/Divider";
import ListItemIcon from "@mui/material/ListItemIcon";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Typography from "@mui/material/Typography";
import { alpha, useTheme, type PaletteMode } from "@mui/material/styles";

import AddWorkingGroupIssueDialog from "@/features/ministry/dashboard/components/add-dashboard-issue-dialog/add-dashboard-issue-dialog";
import {
  AddIssueIcon,
  ChevronDownIcon,
  ChevronRightIcon,
  PlusThinIcon,
  RequestMeetingIcon,
  UploadTrayIcon,
} from "@/features/ministry/dashboard/components/dashboard-icons";

export type ActionMenuItem = {
  disabled?: boolean;
  dividerAbove?: boolean;
  icon?: ReactNode;
  label: string;
  onClick?: () => void;
  showChevron?: boolean;
};

type ActionMenuButtonProps = {
  items: ActionMenuItem[];
  label: string;
  menuAlign?: "left" | "right";
  startIcon: ReactNode;
  variant?: "outline" | "filled";
};

function getMenuPaperSx(mode: PaletteMode) {
  return {
    mt: 0.75,
    borderRadius: "14px",
    overflow: "hidden",
    border:
      mode === "dark"
        ? "1px solid rgba(255,255,255,0.08)"
        : "1px solid rgba(15,23,42,0.08)",
    boxShadow:
      mode === "dark"
        ? "0 18px 40px rgba(0,0,0,0.42)"
        : "0 14px 34px rgba(15,23,42,0.12)",
    backgroundImage: "none",
  };
}

export function ActionMenuButton({
  items,
  label,
  menuAlign = "left",
  startIcon,
  variant = "outline",
}: ActionMenuButtonProps) {
  const theme = useTheme();
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);

  const open = Boolean(anchorEl);
  const isFilled = variant === "filled";
  const isMenuRightAligned = menuAlign === "right";

  function handleOpen(event: MouseEvent<HTMLElement>) {
    setAnchorEl(event.currentTarget);
  }

  function handleClose() {
    setAnchorEl(null);
  }

  return (
    <>
      <ButtonBase
        onClick={handleOpen}
        disableRipple
        sx={{
          minWidth: isFilled ? 92 : 88,
          height: 40,
          px: isFilled ? 1.75 : 1.5,
          borderRadius: "8px",
          border: isFilled
            ? "1px solid #1D69B4"
            : `1px solid ${alpha(theme.palette.primary.main, 0.6)}`,
          bgcolor: isFilled ? "#1D69B4" : theme.palette.background.paper,
          color: isFilled
            ? "#ffffff"
            : theme.palette.mode === "dark"
              ? theme.palette.primary.light
              : theme.palette.primary.main,
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 1,
          boxShadow: open
            ? isFilled
              ? "0 6px 18px rgba(11,37,69,0.28)"
              : `0 6px 18px ${alpha(theme.palette.primary.main, 0.12)}`
            : isFilled
              ? "none"
              : "0 1px 2px rgba(15,23,42,0.04)",
          transition: "all 0.2s ease",
          "&:hover": {
            bgcolor: isFilled
              ? "#1D59B1"
              : alpha(theme.palette.primary.main, 0.04),
          },
        }}
      >
        <Box
          sx={{
            display: "inline-flex",
            alignItems: "center",
            gap: 1,
            minWidth: 0,
          }}
        >
          <Box
            sx={{
              display: "inline-flex",
              alignItems: "center",
              color: "inherit",
            }}
          >
            {startIcon}
          </Box>

          <Typography
            sx={{
              color: "inherit",
              fontSize: 14,
              fontWeight: 600,
              lineHeight: 1,
              whiteSpace: "nowrap",
            }}
          >
            {label}
          </Typography>
        </Box>

        <ChevronDownIcon
          sx={{
            fontSize: 18,
            color: "inherit",
            flexShrink: 0,
            transform: open ? "rotate(180deg)" : "rotate(0deg)",
            transition: "transform 0.2s ease",
          }}
        />
      </ButtonBase>

      <Menu
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: isMenuRightAligned ? "right" : "left",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: isMenuRightAligned ? "right" : "left",
        }}
        slotProps={{
          paper: {
            sx: {
              ...getMenuPaperSx(theme.palette.mode),
              minWidth: isFilled ? 168 : 126,
              mt: 0.75,
            },
          },
          list: {
            dense: false,
            sx: { py: 0.75, px: 0.75 },
          },
        }}
      >
        {items.map((item, index) => (
          <Fragment key={`${label}-${item.label}-${index}`}>
            {item.dividerAbove ? (
              <Divider
                sx={{
                  my: 0.5,
                  borderColor:
                    theme.palette.mode === "dark"
                      ? "rgba(255,255,255,0.08)"
                      : "rgba(15,23,42,0.08)",
                }}
              />
            ) : null}

            <MenuItem
              disabled={item.disabled}
              onClick={() => {
                handleClose();
                item.onClick?.();
              }}
              sx={{
                minHeight: 44,
                px: 1,
                py: 0.625,
                gap: 1,
                borderRadius: "10px",
                color: item.disabled
                  ? theme.palette.text.disabled
                  : theme.palette.text.primary,
                justifyContent: "space-between",
                transition: "background-color 0.2s ease",
                "&:hover": {
                  bgcolor: alpha(theme.palette.primary.main, 0.06),
                },
                "&.Mui-disabled": {
                  opacity: 1,
                  color: theme.palette.text.disabled,
                },
              }}
            >
              <Box
                sx={{
                  minWidth: 0,
                  flex: 1,
                  display: "flex",
                  alignItems: "center",
                  gap: 1,
                }}
              >
                {item.icon ? (
                  <ListItemIcon
                    sx={{
                      minWidth: 22,
                      color: item.disabled
                        ? theme.palette.text.disabled
                        : theme.palette.text.secondary,
                    }}
                  >
                    {item.icon}
                  </ListItemIcon>
                ) : null}

                <Typography
                  sx={{
                    minWidth: 0,
                    fontSize: 14,
                    fontWeight: 500,
                    color: "inherit",
                    whiteSpace: "nowrap",
                  }}
                >
                  {item.label}
                </Typography>
              </Box>

              {item.showChevron ? (
                <ChevronRightIcon
                  sx={{
                    ml: 1,
                    fontSize: 18,
                    color: item.disabled
                      ? theme.palette.text.disabled
                      : theme.palette.text.secondary,
                  }}
                />
              ) : null}
            </MenuItem>
          </Fragment>
        ))}
      </Menu>
    </>
  );
}

const exportItems: ActionMenuItem[] = [
  { label: "CSV" },
  { label: "XLSX" },
  { label: "Image" },
];

export function WorkingGroupActions() {
  const theme = useTheme();
  const [openAddIssue, setOpenAddIssue] = useState(false);

  const newItems: ActionMenuItem[] = [
    {
      label: "Add Issue",
      icon: <AddIssueIcon sx={{ fontSize: 18 }} />,
      showChevron: true,
      onClick: () => setOpenAddIssue(true),
    },
    {
      label: "Request Meeting",
      icon: <RequestMeetingIcon sx={{ fontSize: 18 }} />,
      dividerAbove: true,
      showChevron: true,
    },
  ];

  return (
    <>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          alignItems: { xs: "flex-start", md: "flex-end" },
          gap: 0.75,
        }}
      >
        <Box sx={{ display: "flex", flexWrap: "wrap", gap: 1 }}>
          <ActionMenuButton
            label="Export"
            startIcon={<UploadTrayIcon sx={{ fontSize: 18 }} />}
            items={exportItems}
          />

          <ActionMenuButton
            label="New"
            startIcon={<PlusThinIcon sx={{ fontSize: 18 }} />}
            items={newItems}
            variant="filled"
            menuAlign="right"
          />
        </Box>

        <Typography sx={{ fontSize: 11, color: theme.palette.text.secondary }}>
          <b>Last updated:</b> 14 September 2025, 23:00
        </Typography>
      </Box>

      <AddWorkingGroupIssueDialog
        open={openAddIssue}
        onClose={() => setOpenAddIssue(false)}
      />
    </>
  );
}