"use client";

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

import AutorenewOutlinedIcon from "@mui/icons-material/AutorenewOutlined";
import MoreVertIcon from "@mui/icons-material/MoreVert";
import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import IconButton from "@mui/material/IconButton";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import { IssueStatusBadge } from "@/components/ui/issue-status-badge";

import type { MinistryProgressReportIssueRow } from "./progress-report-issues-data";

function isKhmerText(value: string) {
  return /[\u1780-\u17FF]/.test(value);
}

export function IssuesTextCell({
  value,
  muted = false,
}: {
  value: string;
  muted?: boolean;
}) {
  const isEmpty = !value || value === "No data" || value === "-";

  return (
    <Typography
      className={isKhmerText(value) ? "font-kh" : undefined}
      noWrap
      sx={{
        width: "100%",
        fontSize: muted || isEmpty ? 12 : 13,
        fontWeight: muted || isEmpty ? 400 : 500,
        lineHeight: "22px",
        color: isEmpty
          ? "var(--mr-muted, #535862)"
          : muted
            ? "var(--mr-muted, #535862)"
            : "var(--mr-text, #181d27)",
        overflow: "hidden",
        textOverflow: "ellipsis",
      }}
    >
      {value || "No data"}
    </Typography>
  );
}

export function IssuesStatusCell({
  status,
}: {
  status: MinistryProgressReportIssueRow["status"];
}) {
  return <IssueStatusBadge status={status} />;
}

export function IssuesAgencyCell({
  name,
  logo,
  logoSize = 24,
}: {
  name: string;
  logo?: string | null;
  logoSize?: number;
}) {
  const isEmpty = !name || name === "No data" || name === "-";

  if (isEmpty) {
    return <IssuesTextCell value="No data" muted />;
  }

  return (
    <Box sx={{ display: "flex", alignItems: "center", gap: "20px", minWidth: 0 }}>
      {logo ? (
        <Box
          component="img"
          src={logo}
          alt={name}
          sx={{
            width: logoSize,
            height: logoSize,
            borderRadius: "50%",
            objectFit: "cover",
            flexShrink: 0,
          }}
        />
      ) : null}
      <Typography
        noWrap
        sx={{
          fontSize: 13,
          fontWeight: 500,
          color: "var(--mr-text, #181d27)",
        }}
      >
        {name}
      </Typography>
    </Box>
  );
}

export function IssuesUpdateActionCell({
  onUpdate,
  label = "Update Issue",
  icon = <AutorenewOutlinedIcon sx={{ fontSize: 24 }} />,
}: {
  onUpdate?: () => void;
  label?: string;
  icon?: ReactNode;
}) {
  return (
    <Button
      startIcon={icon}
      onClick={onUpdate}
      sx={{
        color: "var(--mr-muted, #717680)",
        textTransform: "none",
        fontSize: 12,
        fontWeight: 400,
        px: 0.5,
        minWidth: 0,
        whiteSpace: "nowrap",
        "& .MuiButton-startIcon": { mr: 0.5 },
        "&:hover": {
          bgcolor: "transparent",
          color: "var(--mr-blue, #1a64a8)",
        },
      }}
    >
      {label}
    </Button>
  );
}

export function IssuesUpdateMenuActionCell({
  onUpdate,
  onViewComment,
  updateLabel = "Update RGC Decision",
  viewCommentLabel = "View Comment",
}: {
  onUpdate?: () => void;
  onViewComment?: () => void;
  updateLabel?: string;
  viewCommentLabel?: string;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const [anchorElement, setAnchorElement] = useState<HTMLElement | null>(null);
  const isOpen = Boolean(anchorElement);

  function openMenu(event: MouseEvent<HTMLElement>) {
    event.stopPropagation();
    setAnchorElement(event.currentTarget);
  }

  function closeMenu() {
    setAnchorElement(null);
  }

  return (
    <>
      <IconButton
        size="small"
        aria-label="Open actions"
        aria-haspopup="menu"
        aria-expanded={isOpen ? "true" : undefined}
        onClick={openMenu}
        sx={{ color: "text.secondary" }}
      >
        <MoreVertIcon sx={{ fontSize: 20 }} />
      </IconButton>

      <Menu
        anchorEl={anchorElement}
        open={isOpen}
        onClose={closeMenu}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        transformOrigin={{ vertical: "top", horizontal: "right" }}
        slotProps={{
          paper: {
            sx: {
              mt: 0.5,
              minWidth: 200,
              borderRadius: "12px",
              border: `1px solid ${isDark ? alpha("#ffffff", 0.12) : "#f5f5f5"}`,
              bgcolor: isDark ? "#101828" : "#ffffff",
              boxShadow: isDark
                ? "0 12px 30px rgba(0, 0, 0, 0.5)"
                : "0px 0px 10.6px rgba(0, 0, 0, 0.1)",
            },
          },
        }}
      >
        {onViewComment ? (
          <MenuItem
            onClick={() => {
              closeMenu();
              onViewComment();
            }}
            sx={{
              minHeight: 44,
              px: 2,
              gap: 1.5,
              fontSize: 13,
              fontWeight: 500,
              color: isDark ? alpha("#ffffff", 0.86) : "#414651",
            }}
          >
            <VisibilityOutlinedIcon
              sx={{
                fontSize: 20,
                color: isDark ? alpha("#ffffff", 0.72) : "#717680",
              }}
            />
            {viewCommentLabel}
          </MenuItem>
        ) : null}
        <MenuItem
          onClick={() => {
            closeMenu();
            onUpdate?.();
          }}
          sx={{
            minHeight: 44,
            px: 2,
            gap: 1.5,
            fontSize: 13,
            fontWeight: 500,
            color: isDark ? alpha("#ffffff", 0.86) : "#414651",
          }}
        >
          <AutorenewOutlinedIcon
            sx={{
              fontSize: 20,
              color: isDark ? alpha("#ffffff", 0.72) : "#717680",
            }}
          />
          {updateLabel}
        </MenuItem>
      </Menu>
    </>
  );
}
