"use client";

import { useRouter } from "next/navigation";

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

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

import type { CdcIssueMatrixRow } from "./cdc-issue-matrix-data";
import type { CdcIssueMatrixLanguage } from "./cdc-issue-matrix-i18n";

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

const CDC_ISSUE_MATRIX_ACTION_ACCESS = {
  canViewDetail: true,
  canEdit: false,
  canSendRequest: false,
  canRemove: false,
} as const;

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

function toActionIssueRow(row: CdcIssueMatrixRow): IssueRow {
  return {
    id: row.id,
    issue: row.issue,
    category: row.category,
    description: row.issueDescription,
    recommendation: row.recommendation,
    governmentDecision: row.governmentDecision,
    status: row.status,
    primaryAgency: row.primaryAgency,
    primaryAgencyLogo: row.primaryAgencyImage,
    issueReference: "",
  };
}

function noop() {
  // Read-only cell renderer; controlled checkbox still needs an onChange
  // handler to avoid the React "missing onChange" warning.
}

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

  if (!value || value === "-") {
    return (
      <Typography sx={{ color: theme.palette.text.primary, fontSize: 13 }}>
        -
      </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 PlenaryEscalationCell({ checked }: { checked: boolean }) {
  return (
    <Box sx={{ display: "flex", justifyContent: "center", width: "100%" }}>
      <AppCheckbox checked={checked} onChange={noop} />
    </Box>
  );
}

export function CdcIssueMatrixActionCell({
  row,
  language,
}: {
  row: CdcIssueMatrixRow;
  language: CdcIssueMatrixLanguage;
}) {
  const router = useRouter();
  const wgLanguage = toWgIssuesLanguage(language);

  return (
    <ActionCell
      access={CDC_ISSUE_MATRIX_ACTION_ACCESS}
      row={toActionIssueRow(row)}
      language={wgLanguage}
      onViewDetail={() => router.push(`/cdc/cdc-issue-matrix/${row.id}`)}
    />
  );
}

type CdcIssueMatrixTableCellProps = {
  value: string | number | boolean;
  columnKey: string;
  image?: string;
  language: CdcIssueMatrixLanguage;
  row?: CdcIssueMatrixRow;
};

export function CdcIssueMatrixTableCell({
  value,
  columnKey,
  image,
  language,
  row,
}: CdcIssueMatrixTableCellProps) {
  const theme = useTheme();

  if (columnKey === "action" && row) {
    return <CdcIssueMatrixActionCell row={row} language={language} />;
  }

  if (columnKey === "primaryAgency") {
    return <MinistryCell value={String(value)} image={image} />;
  }

  if (columnKey === "plenaryEscalation") {
    return <PlenaryEscalationCell checked={Boolean(value)} />;
  }

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

  if (
    columnKey === "status" &&
    CDC_ISSUE_MATRIX_STATUSES.has(textValue as IssueStatus)
  ) {
    return (
      <StatusBadge
        status={textValue as IssueStatus}
        language={toWgIssuesLanguage(language)}
      />
    );
  }

  const isWrappingTextColumn = columnKey === "workingGroup";

  return (
    <Typography
      sx={{
        color: theme.palette.text.primary,
        fontSize: 13,
        lineHeight: 1.5,
        width: "100%",
        ...(isWrappingTextColumn
          ? {
              whiteSpace: "normal",
              wordBreak: "break-word",
              display: "-webkit-box",
              WebkitLineClamp: 3,
              WebkitBoxOrient: "vertical",
              overflow: "hidden",
            }
          : {
              whiteSpace: "nowrap",
              overflow: "hidden",
              textOverflow: "ellipsis",
            }),
      }}
      title={displayValue}
    >
      {displayValue}
    </Typography>
  );
}
