"use client";

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;
};

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() || "M"
  );
}

function stripHtml(
  value?: string | null,
): string {
  if (!value) {
    return "-";
  }

  return (
    value
      .replace(/<[^>]*>?/gm, "")
      .trim() || "-"
  );
}

function formatDate(
  value?: string | null,
): string {
  if (!value) {
    return "-";
  }

  const text = String(value);

  if (
    /^\d{4}-\d{2}-\d{2}/.test(
      text,
    )
  ) {
    return text.slice(0, 10);
  }

  const date = new Date(value);

  if (
    Number.isNaN(
      date.getTime(),
    )
  ) {
    return text;
  }

  return date
    .toISOString()
    .slice(0, 10);
}

function TextCell({
  value,
  maxWidth,
}: {
  value?: string | null;
  maxWidth?: number;
}) {
  const text = stripHtml(value);

  return (
    <Typography
      title={text}
      sx={{
        maxWidth:
          maxWidth ?? "100%",
        overflow: "hidden",
        textOverflow:
          "ellipsis",
        whiteSpace: "nowrap",
        fontSize: 13,
        fontWeight: 500,
      }}
    >
      {text}
    </Typography>
  );
}

function IssuesCell({
  row,
}: {
  row: RgcDecisionRow;
}) {
  const issueTitles =
    Array.isArray(row.issues)
      ? row.issues
          .map((issue) =>
            String(
              issue.title ?? "",
            ).trim(),
          )
          .filter(Boolean)
      : [];

  const issuesText =
    issueTitles.length > 0
      ? issueTitles.join(", ")
      : "-";

  return (
    <Typography
      title={issuesText}
      sx={{
        maxWidth: "100%",
        overflow: "hidden",
        textOverflow:
          "ellipsis",
        whiteSpace: "nowrap",
        fontSize: 13,
        fontWeight: 500,
      }}
    >
      {issuesText}
    </Typography>
  );
}

function MinistryCell({
  row,
}: {
  row: RgcDecisionRow;
}) {
  const name =
    row.ministry ||
    "Ministry";

  const logoUrl =
    normalizeLogoUrl(
      row.ministryLogo,
    );

  return (
    <Box
      sx={{
        display: "flex",
        alignItems: "center",
        gap: 1.2,
        minWidth: 0,
      }}
    >
      {logoUrl ? (
        <Avatar
          src={logoUrl}
          alt={name}
          sx={{
            width: 28,
            height: 28,
            flexShrink: 0,
            border:
              "1px solid",
            borderColor:
              "divider",
          }}
        />
      ) : (
        <Avatar
          sx={{
            width: 28,
            height: 28,
            flexShrink: 0,
            fontSize: 11,
            fontWeight: 800,
            bgcolor:
              "primary.main",
            color:
              "primary.contrastText",
          }}
        >
          {getInitial(name)}
        </Avatar>
      )}

      <Typography
        title={name}
        sx={{
          minWidth: 0,
          overflow: "hidden",
          textOverflow:
            "ellipsis",
          whiteSpace: "nowrap",
          fontSize: 13,
          fontWeight: 700,
        }}
      >
        {name}
      </Typography>
    </Box>
  );
}

function StatusCell({
  status,
}: {
  status: RgcDecisionStatus;
}) {
  const theme = useTheme();
  const isDark =
    theme.palette.mode === "dark";

  const config: Record<
    RgcDecisionStatus,
    {
      color: string;
      bgcolor: string;
      borderColor: string;
    }
  > = {
    Solved: {
      color: isDark
        ? "#86EFAC"
        : "#16A34A",
      bgcolor: isDark
        ? alpha(
            "#16A34A",
            0.16,
          )
        : "#ECFDF3",
      borderColor: isDark
        ? alpha(
            "#86EFAC",
            0.36,
          )
        : "#BBF7D0",
    },

    "In Progress": {
      color: isDark
        ? "#FCD34D"
        : "#F59E0B",
      bgcolor: isDark
        ? alpha(
            "#F59E0B",
            0.16,
          )
        : "#FFFBEB",
      borderColor: isDark
        ? alpha(
            "#FCD34D",
            0.38,
          )
        : "#FDE68A",
    },

    "Not Addressed": {
      color: isDark
        ? "#FCA5A5"
        : "#DC2626",
      bgcolor: isDark
        ? alpha(
            "#DC2626",
            0.16,
          )
        : "#FEF2F2",
      borderColor: isDark
        ? alpha(
            "#FCA5A5",
            0.38,
          )
        : "#FECACA",
    },
  };

  const style =
    config[status] ??
    config["Not Addressed"];

  return (
    <Chip
      label={status}
      size="small"
      sx={{
        height: 24,
        borderRadius: 99,
        color: style.color,
        bgcolor:
          style.bgcolor,
        border: `1px solid ${style.borderColor}`,
        fontSize: 12,
        fontWeight: 700,

        "& .MuiChip-label":
          {
            px: 1.25,
          },
      }}
    />
  );
}

function VerificationLinkCell({
  row,
}: {
  row: RgcDecisionRow;
}) {
  const link =
    row.verificationLink?.trim() ||
    row.verificationDownloadUrl?.trim();

  if (!link) {
    return (
      <Typography
        sx={{
          fontSize: 13,
          color:
            "text.disabled",
        }}
      >
        -
      </Typography>
    );
  }

  return (
    <Link
      href={link}
      target="_blank"
      rel="noopener noreferrer"
      underline="always"
      title={link}
      sx={{
        display: "block",
        maxWidth: "100%",
        overflow: "hidden",
        textOverflow:
          "ellipsis",
        whiteSpace: "nowrap",
        fontSize: 13,
        fontWeight: 600,
        color:
          "primary.main",
      }}
    >
      View Source
    </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={row.decision}
          maxWidth={390}
        />
      );

    case "issues":
      return (
        <IssuesCell
          row={row}
        />
      );

    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={
            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 (
        <Typography>
          -
        </Typography>
      );
  }
}

export default RgcDecisionTableCell;