"use client";

import Link from "next/link";

import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";

import { AppCheckbox } from "@/components/ui/checkbox";
import { StatusBadge } from "@/features/pswg/working-group-issues/components/table/wg-issues-table-cells";
import type { IssueStatus } from "@/features/pswg/working-group-issues/wg-issues-data";
import type { WgIssuesLanguage } from "@/features/pswg/working-group-issues/wg-issues-i18n";

import {
  issueMatrixText,
  translateIssueMatrixValue,
  type IssueMatrixLanguage,
} from "./issue-matrix-i18n";
import type { IssueMatrixRow } from "./issue-matrix-data";
import {
  IssueMatrixStatusSelectCell,
  PrimaryAgencySelectCell,
  type IssueMatrixEditControl,
} from "./issue-matrix-row-editors";

const ISSUE_MATRIX_STATUSES = new Set<IssueStatus>([
  "Solved",
  "In Progress",
  "Not Addressed",
  "Draft",
  "Saved",
  "New Submission",
]);

const AGENCY_COLUMN_KEYS = new Set([
  "primaryAgency",
  "secondAgency",
  "thirdAgency",
  "fourthAgency",
  "fifthAgency",
]);

function noop() {
  // Read-only checkbox cells still need an onChange handler.
}

function toWgIssuesLanguage(language: IssueMatrixLanguage): WgIssuesLanguage {
  return language === "kh" ? "km" : "en";
}

type IssueMatrixTableCellProps = {
  value: string | number | boolean;
  isLink?: boolean;
  columnKey?: string;
  image?: string;
  detailHref?: string;
  language: IssueMatrixLanguage;
  row?: IssueMatrixRow;
  editControl?: IssueMatrixEditControl;
  plenaryEscalationControl?: IssueMatrixPlenaryEscalationControl;
};

export type IssueMatrixPlenaryEscalationControl = {
  canEscalate: boolean;
  isUpdating: boolean;
  onToggle: (row: IssueMatrixRow, escalated: boolean) => void;
};

function PlenaryEscalationCell({
  row,
  control,
}: {
  row: IssueMatrixRow;
  control?: IssueMatrixPlenaryEscalationControl;
}) {
  const isEditable = Boolean(control?.canEscalate) && row.id > 0;

  return (
    <Box sx={{ display: "flex", justifyContent: "center", width: "100%" }}>
      <AppCheckbox
        checked={row.plenaryEscalation}
        disabled={isEditable && Boolean(control?.isUpdating)}
        onChange={
          isEditable
            ? (event) => control?.onToggle(row, event.target.checked)
            : noop
        }
      />
    </Box>
  );
}

function AgencyCell({ value, image }: { value: string; image?: string }) {
  const theme = useTheme();

  if (!value || value === "-") {
    return (
      <Typography
        sx={{
          color: theme.palette.text.primary,
          fontSize: 13,
          lineHeight: 1.5,
        }}
      >
        -
      </Typography>
    );
  }

  return (
    <Box sx={{ display: "flex", alignItems: "center", gap: 1, minWidth: 0 }}>
      <Box
        component="img"
        src={image || "/images/agencies/default.png"}
        alt={value}
        sx={{
          width: 24,
          height: 24,
          borderRadius: "50%",
          objectFit: "cover",
          flexShrink: 0,
          border: `1px solid ${alpha(theme.palette.divider, 0.8)}`,
          bgcolor:
            theme.palette.mode === "dark"
              ? alpha(theme.palette.primary.main, 0.14)
              : "#E8F4FF",
        }}
      />

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

function ActionCell({
  href,
  language,
}: {
  href: string;
  language: IssueMatrixLanguage;
}) {
  const theme = useTheme();
  const text = issueMatrixText[language] ?? issueMatrixText.en;

  return (
    <Button
      component={Link}
      href={href}
      variant="text"
      startIcon={<VisibilityOutlinedIcon sx={{ fontSize: 17 }} />}
      sx={{
        minWidth: 0,
        height: 32,
        px: 1,
        borderRadius: 1,
        textTransform: "none",
        fontSize: 12,
        fontWeight: 500,
        color: theme.palette.text.secondary,
        whiteSpace: "nowrap",
        "&:hover": {
          bgcolor:
            theme.palette.mode === "dark"
              ? alpha(theme.palette.primary.main, 0.12)
              : "#F3F8FF",
          color: theme.palette.primary.main,
        },
      }}
    >
      {text.viewDetail}
    </Button>
  );
}

export function IssueMatrixTableCell({
  value,
  isLink = false,
  columnKey,
  image,
  detailHref = "#",
  language,
  row,
  editControl,
  plenaryEscalationControl,
}: IssueMatrixTableCellProps) {
  const theme = useTheme();
  const text = issueMatrixText[language] ?? issueMatrixText.en;

  const textValue = String(value);
  const displayValue = translateIssueMatrixValue(textValue, language);

  if (columnKey === "plenaryEscalation" && row) {
    return (
      <PlenaryEscalationCell row={row} control={plenaryEscalationControl} />
    );
  }

  if (columnKey && AGENCY_COLUMN_KEYS.has(columnKey)) {
    if (columnKey === "primaryAgency" && row) {
      return <PrimaryAgencySelectCell row={row} control={editControl} />;
    }

    return <AgencyCell value={textValue} image={image} />;
  }

  if (columnKey === "action") {
    return <ActionCell href={detailHref} language={language} />;
  }

  if (
    columnKey === "status" &&
    ISSUE_MATRIX_STATUSES.has(textValue as IssueStatus)
  ) {
    if (row) {
      return (
        <IssueMatrixStatusSelectCell
          row={row}
          language={language}
          control={editControl}
        />
      );
    }

    return (
      <StatusBadge
        status={textValue as IssueStatus}
        language={toWgIssuesLanguage(language)}
      />
    );
  }

  if (isLink) {
    const isDownload = textValue.toLowerCase() === "download";

    return isDownload ? (
      <Link
        href="#"
        style={{
          color: theme.palette.primary.main,
          fontWeight: 700,
          fontSize: 13,
          textDecoration: "underline",
          textUnderlineOffset: 3,
        }}
      >
        {text.download}
      </Link>
    ) : (
      <Typography
        component="span"
        sx={{
          color: theme.palette.text.secondary,
          fontSize: 13,
          fontWeight: 500,
        }}
      >
        {displayValue}
      </Typography>
    );
  }

  return (
    <Typography
      sx={{
        color: theme.palette.text.primary,
        fontSize: 13,
        lineHeight: 1.5,
        whiteSpace: "nowrap",
        overflow: "hidden",
        textOverflow: "ellipsis",
      }}
      title={displayValue}
    >
      {displayValue}
    </Typography>
  );
}
