"use client";

import { Fragment, useState, type MouseEvent, type 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 { useAppLanguage } from "@/components/providers/app-language-provider";
import AddIssueDialog from "@/features/pswg/plenary/components/add-issue-dialog/add-issue-dialog";
import {
  AddIssueIcon,
  ChevronDownIcon,
  ChevronRightIcon,
  PlusThinIcon,
  RequestMeetingIcon,
  UploadTrayIcon,
} from "@/features/pswg/plenary/components/plenary-icons";
import {
  normalizePlenaryLanguage,
  plenaryText,
} from "@/features/pswg/plenary/plenary-i18n";

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

export function PlenaryActions() {
  const theme = useTheme();
  const { language } = useAppLanguage();

  const currentLanguage = normalizePlenaryLanguage(language);
  const text = plenaryText[currentLanguage];

  const [openAddIssue, setOpenAddIssue] = useState(false);

  const exportItems: PlenaryActionMenuItem[] = [
    { label: text.csv },
    { label: text.xlsx },
    { label: text.image },
  ];

  const newItems: PlenaryActionMenuItem[] = [
    {
      label: text.addIssue,
      icon: <AddIssueIcon sx={{ fontSize: 18 }} />,
      showChevron: true,
      onClick: () => setOpenAddIssue(true),
    },
    {
      label: text.requestMeeting,
      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 }}>
          <PlenaryActionMenuButton
            label={text.export}
            startIcon={<UploadTrayIcon sx={{ fontSize: 18 }} />}
            items={exportItems}
          />

          <PlenaryActionMenuButton
            label={text.newItem}
            startIcon={<PlusThinIcon sx={{ fontSize: 18 }} />}
            items={newItems}
            variant="filled"
            menuAlign="right"
          />
        </Box>

        <Typography sx={{ fontSize: 11, color: theme.palette.text.secondary }}>
          <Box component="span" sx={{ fontWeight: 700 }}>
            {text.lastUpdated}:
          </Box>{" "}
          {text.lastUpdatedDate}
        </Typography>
      </Box>

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

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",
  };
}

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

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

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

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

  const 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>
    </>
  );
}