"use client";

import { useState } from "react";

import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import ButtonBase from "@mui/material/ButtonBase";
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 } from "@mui/material/styles";

import DeleteOutlinedIcon from "@mui/icons-material/DeleteOutlined";
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
import SendOutlinedIcon from "@mui/icons-material/SendOutlined";
import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";

import { dashboardAssets } from "@/components/dashboard/dashboard-assets";
import { DashboardAssetIcon } from "@/components/dashboard/dashboard-asset-icon";
import { getDisplayFileName } from "@/lib/document-file";
import type { IssueRow } from "@/features/pswg/working-group-issues/wg-issues-data";
import {
  tWgIssues,
  type WgIssuesLanguage,
} from "@/features/pswg/working-group-issues/wg-issues-i18n";

// StatusBadge now lives in a shared, reusable component. Re-exported here so
// existing import sites keep working.
export { IssueStatusBadge as StatusBadge } from "@/features/pswg/working-group-issues/components/issue-status-badge";

export function TableText({
  value,
  align = "left",
}: {
  value: string;
  align?: "left" | "center";
}) {
  const theme = useTheme();

  return (
    <Typography
      sx={{
        width: "100%",
        color: theme.palette.text.primary,
        fontSize: 13,
        lineHeight: 1.5,
        whiteSpace: "nowrap",
        overflow: "hidden",
        textOverflow: "ellipsis",
        textAlign: align,
      }}
    >
      {value}
    </Typography>
  );
}

export function AgencyCell({
  agency,
  logo,
}: {
  agency: string;
  logo?: string | null;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const imageSrc = logo || dashboardAssets.primaryAgencyAvatar;

  return (
    <Box sx={{ display: "flex", alignItems: "center", gap: 1, minWidth: 0 }}>
      <Avatar
        src={imageSrc}
        alt={agency}
        sx={{
          width: 24,
          height: 24,
          bgcolor: isDark
            ? alpha(theme.palette.common.white, 0.08)
            : "#E8F4FF",
        }}
      />

      <Typography
        sx={{
          color: theme.palette.text.primary,
          fontSize: 13,
          fontWeight: 600,
          whiteSpace: "nowrap",
          overflow: "hidden",
          textOverflow: "ellipsis",
        }}
      >
        {agency}
      </Typography>
    </Box>
  );
}

function FileReferenceIcon() {
  return (
    <Box sx={{ position: "relative", width: 20, height: 20, flexShrink: 0 }}>
      <DashboardAssetIcon
        src={dashboardAssets.fileReferencePage}
        alt=""
        width={12}
        height={15}
        sx={{ position: "absolute", left: 4, top: 2 }}
      />

      <DashboardAssetIcon
        src={dashboardAssets.fileReferenceEarmark}
        alt=""
        width={5.75}
        height={5.75}
        sx={{ position: "absolute", left: 10, top: 1.5 }}
      />

      <Box
        sx={{
          position: "absolute",
          left: 0,
          top: 7,
          width: 11,
          height: 6,
          borderRadius: "2px",
          bgcolor: "#f04438",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <DashboardAssetIcon
          src={dashboardAssets.fileReferenceLabel}
          alt=""
          width={5}
          height={2}
        />
      </Box>
    </Box>
  );
}

export function ReferenceCell({ label }: { label?: string }) {
  const theme = useTheme();

  if (!label) return null;

  const displayLabel = getDisplayFileName(label, "-");

  return (
    <Box sx={{ display: "inline-flex", alignItems: "center", gap: 1, minWidth: 0 }}>
      <FileReferenceIcon />
      <Typography
        sx={{
          color: theme.palette.text.primary,
          fontSize: 13,
          lineHeight: 1.5,
          whiteSpace: "nowrap",
          overflow: "hidden",
          textOverflow: "ellipsis",
        }}
      >
        {displayLabel}
      </Typography>
    </Box>
  );
}

// Callbacks the row action menu can trigger.
export type WgIssueActionHandlers = {
  onViewDetail?: (row: IssueRow) => void;
  onEdit?: (row: IssueRow) => void;
  onSendRequest?: (row: IssueRow) => void;
  onRemove?: (row: IssueRow) => void;
};

// Row actions are hidden by default. The table enables each action only after
// checking the authenticated user's permissions.
export type WgIssueActionAccess = {
  canViewDetail: boolean;
  canEdit: boolean;
  canSendRequest: boolean;
  canRemove: boolean;
};

export const NO_WG_ISSUE_ACTION_ACCESS: WgIssueActionAccess = {
  canViewDetail: false,
  canEdit: false,
  canSendRequest: false,
  canRemove: false,
};

function isNewSubmissionIssue(row?: IssueRow) {
  return row?.status === "New Submission";
}

// An issue can only be edited while it is still a working draft. Once it has
// been submitted / is in progress / resolved, editing is no longer offered.
function isEditableIssue(row?: IssueRow) {
  return row?.status === "Draft" || row?.status === "Saved";
}

export function ActionCell({
  access = NO_WG_ISSUE_ACTION_ACCESS,
  row,
  language = "en",
  onViewDetail,
  onEdit,
  onSendRequest,
  onRemove,
}: {
  access?: WgIssueActionAccess;
  row?: IssueRow;
  language?: WgIssuesLanguage;
} & WgIssueActionHandlers) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null);

  function closeMenu() {
    setMenuAnchor(null);
  }

  // Close the menu, then run the chosen action with this row (if both exist).
  function runAction(handler?: (row: IssueRow) => void) {
    closeMenu();
    if (row && handler) {
      handler(row);
    }
  }

  const menuItemSx = {
    gap: 1.25,
    px: 2,
    py: 1.25,
    fontSize: 14,
    color: isDark ? alpha("#ffffff", 0.78) : "#414651",
    "& .MuiListItemIcon-root": {
      minWidth: 0,
      color: "inherit",
    },
  };

  const canChangeIssue = !isNewSubmissionIssue(row);
  // Edit is only offered for editable (Draft / Saved) issues.
  const canEdit = access.canEdit && isEditableIssue(row);
  const canRemove = access.canRemove && canChangeIssue;

  const hasVisibleAction =
    access.canViewDetail ||
    canEdit ||
    access.canSendRequest ||
    canRemove;

  if (!hasVisibleAction) {
    return null;
  }

  return (
    <>
      <ButtonBase
        aria-label={tWgIssues(language, "moreActions")}
        onClick={(event) => setMenuAnchor(event.currentTarget)}
        sx={{
          width: 24,
          height: 24,
          borderRadius: "4px",
          display: "grid",
          placeItems: "center",
          bgcolor: isDark ? alpha("#ffffff", 0.04) : "transparent",
          "&:hover": {
            bgcolor: isDark ? alpha("#ffffff", 0.08) : "#f5f5f5",
          },
        }}
      >
        <DashboardAssetIcon
          src={dashboardAssets.actionMoreVertical}
          alt={tWgIssues(language, "moreActions")}
          width={3.33}
          height={15}
        />
      </ButtonBase>

      <Menu
        anchorEl={menuAnchor}
        open={Boolean(menuAnchor)}
        onClose={closeMenu}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        transformOrigin={{ vertical: "top", horizontal: "right" }}
        slotProps={{
          paper: {
            sx: {
              minWidth: 200,
              borderRadius: "10px",
              boxShadow: isDark
                ? "0 0 20px rgba(0,0,0,0.45)"
                : "0 4px 16px rgba(0,0,0,0.12)",
            },
          },
        }}
      >
        {access.canViewDetail ? (
          <MenuItem onClick={() => runAction(onViewDetail)} sx={menuItemSx}>
            <ListItemIcon>
              <VisibilityOutlinedIcon sx={{ fontSize: 20 }} />
            </ListItemIcon>
            {tWgIssues(language, "viewDetail")}
          </MenuItem>
        ) : null}

        {canEdit ? (
          <MenuItem onClick={() => runAction(onEdit)} sx={menuItemSx}>
            <ListItemIcon>
              <EditOutlinedIcon sx={{ fontSize: 20 }} />
            </ListItemIcon>
            {tWgIssues(language, "edit")}
          </MenuItem>
        ) : null}

        {access.canSendRequest ? (
          <MenuItem onClick={() => runAction(onSendRequest)} sx={menuItemSx}>
            <ListItemIcon>
              <SendOutlinedIcon sx={{ fontSize: 20 }} />
            </ListItemIcon>
            {tWgIssues(language, "sendRequest")}
          </MenuItem>
        ) : null}

        {canRemove ? (
          <MenuItem
            onClick={() => runAction(onRemove)}
            sx={{ ...menuItemSx, color: "#f04438" }}
          >
            <ListItemIcon>
              <DeleteOutlinedIcon sx={{ fontSize: 20 }} />
            </ListItemIcon>
            {tWgIssues(language, "removeIssue")}
          </MenuItem>
        ) : null}
      </Menu>
    </>
  );
}
