"use client";

import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import { alpha } from "@mui/material/styles";

import { IssueStatusBadge } from "@/components/ui/issue-status-badge";
import type { MeetingCalendarLabels } from "@/features/ministry/meeting-request/meeting-request-i18n";

const ISSUE_TABLE_GRID =
  "52px 241px 292px 501px 440px 215px 215px 215px 215px 215px 215px 184px";

const ISSUE_TABLE_MIN_WIDTH = 3000;
const ISSUE_TABLE_BORDER = "#f5f5f5";
const ISSUE_TABLE_HEADER_BG = "#ddedfb";

export type MeetingDetailIssueTableRow = {
  id?: number | string;
  title?: string | null;
  issue?: string | null;
  description?: string | null;
  recommendation?: string | null;
  status?: string | null;
  primaryAgency?: string | null;
  primaryAgencyLogo?: string | null;
  secondAgency?: string | null;
  secondAgencyLogo?: string | null;
  thirdAgency?: string | null;
  thirdAgencyLogo?: string | null;
  fourthAgency?: string | null;
  fourthAgencyLogo?: string | null;
  fifthAgency?: string | null;
  fifthAgencyLogo?: string | null;
  governmentAgencies?: Array<{
    agencyOrder?: number | null;
    stakeholder?: {
      name?: string | null;
      logo?: string | null;
    } | null;
  }> | null;
  category?: { name?: string | null } | string | null;
  issueStatus?: { name?: string | null } | null;
};

type AgencySlot = {
  name: string;
  logo: string;
};

type Props = {
  issues: MeetingDetailIssueTableRow[];
  isDark: boolean;
  onViewIssue: (issue: MeetingDetailIssueTableRow) => void;
  stripHtmlText: (value?: string | null) => string;
  getIssueAgency: (issue: MeetingDetailIssueTableRow, order: number) => AgencySlot;
  getMediaUrl: (path?: string | null) => string;
  labels: MeetingCalendarLabels;
  statusLabels: Readonly<Record<string, string>>;
};

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

function cellBorder(isDark: boolean) {
  return isDark ? alpha("#ffffff", 0.08) : ISSUE_TABLE_BORDER;
}

function IssueTableTextCell({
  value,
  isDark,
  bold = true,
}: {
  value: string;
  isDark: boolean;
  bold?: boolean;
}) {
  return (
    <Typography
      className={isKhmerText(value) ? "font-kh" : undefined}
      noWrap
      sx={{
        width: "100%",
        overflow: "hidden",
        textOverflow: "ellipsis",
        fontSize: 13,
        fontWeight: bold ? 500 : 400,
        lineHeight: 1.24,
        color: isDark ? "#f9fafb" : "#181d27",
      }}
    >
      {value}
    </Typography>
  );
}

function IssueTableAgencyCell({
  agency,
  isDark,
  getMediaUrl,
  emptyLabel,
}: {
  agency: AgencySlot;
  isDark: boolean;
  getMediaUrl: (path?: string | null) => string;
  emptyLabel: string;
}) {
  const name = agency.name?.trim();
  const isEmpty = !name || name === "No data";

  if (isEmpty) {
    return (
      <Typography
        sx={{
          fontSize: 12,
          fontWeight: 500,
          color: isDark ? "#d0d5dd" : "#181d27",
        }}
      >
        {emptyLabel}
      </Typography>
    );
  }

  const logoUrl = getMediaUrl(agency.logo);

  return (
    <Box sx={{ display: "flex", alignItems: "center", gap: 1, minWidth: 0, width: "100%" }}>
      {logoUrl ? (
        <Box
          component="img"
          src={logoUrl}
          alt={name}
          sx={{
            width: 19,
            height: 19,
            borderRadius: "50%",
            objectFit: "cover",
            flexShrink: 0,
          }}
        />
      ) : null}
      <Typography
        noWrap
        sx={{
          fontSize: 12,
          fontWeight: 500,
          color: isDark ? "#f9fafb" : "#181d27",
        }}
      >
        {name}
      </Typography>
    </Box>
  );
}

function IssueTableHeaderRow({
  isDark,
  headers,
}: {
  isDark: boolean;
  headers: string[];
}) {
  const border = cellBorder(isDark);

  return (
    <Box
      sx={{
        display: "grid",
        gridTemplateColumns: ISSUE_TABLE_GRID,
        minWidth: ISSUE_TABLE_MIN_WIDTH,
        bgcolor: isDark ? alpha("#ffffff", 0.07) : ISSUE_TABLE_HEADER_BG,
      }}
    >
      {headers.map((header, index) => (
        <Box
          key={header}
          sx={{
            minHeight: 50,
            display: "flex",
            alignItems: "center",
            px: index === 0 ? "15px" : 2,
            borderTop: `1px solid ${border}`,
            borderRight: `1px solid ${border}`,
            borderBottom: `1px solid ${border}`,
            borderLeft: index === 0 ? `1px solid ${border}` : undefined,
          }}
        >
          <Typography
            noWrap
            sx={{
              fontSize: 12,
              lineHeight: 1.24,
              fontWeight: 400,
              color: isDark ? "#d0d5dd" : "#717680",
            }}
          >
            {header}
          </Typography>
        </Box>
      ))}
    </Box>
  );
}

function IssueTableDataRow({
  issue,
  index,
  isDark,
  getIssueAgency,
  getMediaUrl,
  stripHtmlText,
  onViewIssue,
  labels,
  statusLabels,
}: {
  issue: MeetingDetailIssueTableRow;
  index: number;
  isDark: boolean;
  getIssueAgency: Props["getIssueAgency"];
  getMediaUrl: Props["getMediaUrl"];
  stripHtmlText: Props["stripHtmlText"];
  onViewIssue: Props["onViewIssue"];
  labels: MeetingCalendarLabels;
  statusLabels: Readonly<Record<string, string>>;
}) {
  const border = cellBorder(isDark);
  const agencies = [1, 2, 3, 4, 5].map((order) => getIssueAgency(issue, order));
  const issueTitle = stripHtmlText(issue.title || issue.issue);
  const description = stripHtmlText(issue.description);
  const recommendation = stripHtmlText(issue.recommendation);
  const category =
    (typeof issue.category === "string"
      ? issue.category
      : issue.category?.name) || "-";
  const status = issue.status || issue.issueStatus?.name || "Not Addressed";

  const bodyCellSx = {
    minHeight: 60,
    display: "flex",
    alignItems: "center",
    borderRight: `1px solid ${border}`,
    borderBottom: `1px solid ${border}`,
    minWidth: 0,
  } as const;

  return (
    <Box
      sx={{
        display: "grid",
        gridTemplateColumns: ISSUE_TABLE_GRID,
        minWidth: ISSUE_TABLE_MIN_WIDTH,
        bgcolor: isDark ? "#101828" : "#ffffff",
      }}
    >
      <Box
        sx={{
          ...bodyCellSx,
          justifyContent: "center",
          pl: 2,
          pr: 3,
          borderLeft: `1px solid ${border}`,
        }}
      >
        <IssueTableTextCell value={String(index + 1)} isDark={isDark} />
      </Box>

      <Box sx={{ ...bodyCellSx, p: 2 }}>
        <IssueTableTextCell value={issueTitle} isDark={isDark} />
      </Box>

      <Box sx={{ ...bodyCellSx, p: 2 }}>
        <IssueTableTextCell value={category} isDark={isDark} />
      </Box>

      <Box sx={{ ...bodyCellSx, p: 2 }}>
        <IssueTableTextCell value={description} isDark={isDark} />
      </Box>

      <Box sx={{ ...bodyCellSx, p: 2 }}>
        <IssueTableTextCell value={recommendation} isDark={isDark} />
      </Box>

      {agencies.map((agency, agencyIndex) => (
        <Box
          key={`${String(issue.id ?? index)}-agency-${agencyIndex}`}
          sx={{ ...bodyCellSx, pl: 2, pr: 3 }}
        >
          <IssueTableAgencyCell
            agency={agency}
            isDark={isDark}
            getMediaUrl={getMediaUrl}
            emptyLabel={labels.issueTable.notUploaded}
          />
        </Box>
      ))}

      <Box sx={{ ...bodyCellSx, pl: 2, pr: 3 }}>
        <IssueStatusBadge
          status={status}
          label={statusLabels[status] ?? status}
        />
      </Box>

      <Box sx={{ ...bodyCellSx, pl: 2 }}>
        <Button
          type="button"
          onClick={() => onViewIssue(issue)}
          startIcon={<VisibilityOutlinedIcon sx={{ fontSize: 24 }} />}
          sx={{
            width: 160,
            height: 40,
            justifyContent: "flex-start",
            px: 2,
            color: isDark ? "#d0d5dd" : "#717680",
            textTransform: "none",
            fontSize: 12,
            fontWeight: 400,
            lineHeight: 1.24,
            borderRadius: "6px",
            "& .MuiButton-startIcon": {
              mr: 0.5,
            },
            "&:hover": {
              bgcolor: isDark ? alpha("#ffffff", 0.08) : "#f5f8ff",
            },
          }}
        >
          {labels.issueTable.viewDetail}
        </Button>
      </Box>
    </Box>
  );
}

export function MeetingDetailIssuesTable({
  issues,
  isDark,
  onViewIssue,
  stripHtmlText,
  getIssueAgency,
  getMediaUrl,
  labels,
  statusLabels,
}: Props) {
  return (
    <Box
      sx={{
        border: `1px solid ${isDark ? alpha("#ffffff", 0.12) : "#e9eaeb"}`,
        borderRadius: "12px",
        overflow: "hidden",
        bgcolor: isDark ? "#101828" : "#ffffff",
      }}
    >
      <Box sx={{ width: "100%", overflowX: "auto" }}>
        <IssueTableHeaderRow
          isDark={isDark}
          headers={[
            labels.issueTable.no,
            labels.issueTable.issue,
            labels.issueTable.categoryOfIssue,
            labels.issueTable.issueDescription,
            labels.issueTable.recommendation,
            labels.issueTable.govtPrimaryAgency,
            labels.issueTable.govtSecondAgency,
            labels.issueTable.govtThirdAgency,
            labels.issueTable.govtFourthAgency,
            labels.issueTable.govtFifthAgency,
            labels.issueTable.status,
            labels.issueTable.action,
          ]}
        />
        {issues.length > 0 ? (
          issues.map((issue, index) => (
            <IssueTableDataRow
              key={String(issue.id ?? index)}
              issue={issue}
              index={index}
              isDark={isDark}
              getIssueAgency={getIssueAgency}
              getMediaUrl={getMediaUrl}
              stripHtmlText={stripHtmlText}
              onViewIssue={onViewIssue}
              labels={labels}
              statusLabels={statusLabels}
            />
          ))
        ) : (
          <Typography
            sx={{
              px: 2,
              py: 2.5,
              fontSize: 13,
              color: isDark ? "#d0d5dd" : "#717680",
            }}
          >
            {labels.detail.noIssuesSubmitted}
          </Typography>
        )}
      </Box>
    </Box>
  );
}
