"use client";

import { useMemo, useState } from "react";
import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Chip from "@mui/material/Chip";
import Link from "@mui/material/Link";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";
import type { RgcDecisionRow, RgcDecisionStatus } from "../data/rgc-decision-data";
import type { RgcDecisionColumnId } from "./rgc-decision-table-config";

type Props = {
  row: RgcDecisionRow;
  columnId: RgcDecisionColumnId;
  displayNumber: number;
  onViewDetail?: (row: RgcDecisionRow) => void;
};

// Function សម្រាប់លុប HTML Tags
function stripHtml(html?: string | null): string {
  if (!html) return "";
  const text = html.replace(/<[^>]*>?/gm, ' ');
  return text.replace(/\s+/g, ' ').trim();
}

const FILE_BASE_URL =
  process.env.NEXT_PUBLIC_FILE_URL?.replace(/\/$/, "") ??
  process.env.NEXT_PUBLIC_API_URL?.replace(/\/api\/v1\/?$/, "").replace(/\/$/, "") ??
  "http://localhost:3001";

function normalizeLogoUrl(value?: string | null): string {
  const logo = String(value ?? "").trim();
  if (!logo) return "";
  if (/^(https?:|data:|blob:)/.test(logo)) return logo;
  return `${FILE_BASE_URL}${logo.startsWith("/") ? logo : `/${logo}`}`;
}

function getInitial(value?: string | null): string {
  return Array.from(String(value ?? "").trim())[0]?.toUpperCase() ?? "?";
}

function formatDate(value?: string | null): string {
  const text = String(value ?? "").trim();
  if (!text) return "-";
  const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(text);
  if (!match) return text;
  const date = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
  if (Number.isNaN(date.getTime())) return text;
  return new Intl.DateTimeFormat("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  }).format(date);
}

function TextCell({ value, maxWidth }: { value?: string | null; maxWidth?: number }) {
  const theme = useTheme();
  const displayValue = String(value ?? "").trim() || "-";
  return (
    <Typography
      title={displayValue}
      sx={{
        width: "100%",
        maxWidth,
        color: theme.palette.text.primary,
        fontSize: 13,
        fontWeight: 500,
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap",
      }}
    >
      {displayValue}
    </Typography>
  );
}

function MinistryCell({ row }: { row: RgcDecisionRow }) {
  const theme = useTheme();
  const logoUrl = useMemo(() => normalizeLogoUrl(row.ministryLogo), [row.ministryLogo]);
  const [failedLogoUrl, setFailedLogoUrl] = useState<string | null>(null);
  const showLogo = Boolean(logoUrl) && failedLogoUrl !== logoUrl;

  return (
    <Box sx={{ minWidth: 0, display: "flex", alignItems: "center", gap: 1.1 }}>
      <Avatar
        src={showLogo ? logoUrl : undefined}
        slotProps={{ img: { onError: () => setFailedLogoUrl(logoUrl) } }}
        sx={{
          width: 32,
          height: 32,
          flexShrink: 0,
          border: "1px solid",
          borderColor: theme.palette.primary.main,
          bgcolor: alpha(theme.palette.primary.main, 0.08),
          color: theme.palette.primary.main,
          fontSize: 12,
          fontWeight: 700,
          "& img": { width: "100%", height: "100%", objectFit: "contain", padding: "2px" },
        }}
      >
        {!showLogo ? getInitial(row.ministry) : null}
      </Avatar>
      <TextCell value={row.ministry} maxWidth={155} />
    </Box>
  );
}

function StatusCell({ status }: { status: RgcDecisionStatus }) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const styles =
    status === "Solved"
      ? { color: isDark ? "#4ADE80" : "#16A34A", borderColor: "#86EFAC", backgroundColor: isDark ? alpha("#22C55E", 0.12) : "#F0FDF4" }
      : status === "In Progress"
        ? { color: isDark ? "#FBBF24" : "#D97706", borderColor: "#FCD34D", backgroundColor: isDark ? alpha("#F59E0B", 0.12) : "#FFFBEB" }
        : { color: isDark ? "#FF6B6B" : "#EF4444", borderColor: "#FCA5A5", backgroundColor: isDark ? alpha("#EF4444", 0.13) : "#FEF2F2" };

  return (
    <Chip
      label={status}
      size="small"
      variant="outlined"
      sx={{
        minWidth: status === "Not Addressed" ? 118 : 104,
        height: 25,
        color: styles.color,
        borderColor: styles.borderColor,
        bgcolor: styles.backgroundColor,
        borderRadius: "999px",
        "& .MuiChip-label": { px: 1.2, fontSize: 11, fontWeight: 700 },
      }}
    />
  );
}

function VerificationLinkCell({ row }: { row: RgcDecisionRow }) {
  const theme = useTheme();
  const link = row.verificationLink?.trim() || row.verificationDownloadUrl?.trim() || "";
  if (!link) return <TextCell value="-" />;

  return (
    <Link
      href={link}
      target="_blank"
      rel="noopener noreferrer"
      underline="always"
      title={link}
      onClick={(event) => event.stopPropagation()}
      sx={{
        display: "block",
        maxWidth: 190,
        color: theme.palette.primary.main,
        fontSize: 13,
        fontWeight: 600,
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap",
      }}
    >
      Download
    </Link>
  );
}

export function RgcDecisionTableCell({ row, columnId, displayNumber, onViewDetail }: Props) {
  switch (columnId) {
    case "number":
      return <Typography sx={{ textAlign: "center", fontSize: 13, fontWeight: 700 }}>{displayNumber}</Typography>;
    case "ministry":
      return <MinistryCell row={row} />;
    case "decision":
      return <TextCell value={stripHtml(row.decision)} maxWidth={390} />;
    case "meetingDate":
      return <TextCell value={formatDate(row.meetingDate)} />;
    case "category":
      return <TextCell value={row.category || row.measureCategory} maxWidth={145} />;
    case "status":
      return <StatusCell status={row.status} />;
    case "indicator":
      return <TextCell value={row.indicator} maxWidth={150} />;
    case "focalPerson":
      return <TextCell value={row.focalPerson} maxWidth={160} />;
    case "sourceOfVerification":
      return <TextCell value={stripHtml(row.sourceOfVerification)} maxWidth={210} />;
    case "verificationLink":
      return <VerificationLinkCell row={row} />;
    case "action":
      return (
        <Button
          variant="text"
          startIcon={<VisibilityOutlinedIcon sx={{ fontSize: 17 }} />}
          onClick={(event) => {
            event.stopPropagation();
            onViewDetail?.(row);
          }}
          sx={{ minWidth: 0, px: 0.5, textTransform: "none", whiteSpace: "nowrap", fontSize: 12, fontWeight: 600 }}
        >
          View Detail
        </Button>
      );
    default:
      return <Box>-</Box>;
  }
}

export default RgcDecisionTableCell;