"use client";

import {
  useMemo,
  useState,
  type ReactNode,
} from "react";

import {
  useParams,
  useRouter,
} from "next/navigation";

import AccountBalanceOutlinedIcon from "@mui/icons-material/AccountBalanceOutlined";
import ArrowBackIosNewRoundedIcon from "@mui/icons-material/ArrowBackIosNewRounded";
import CalendarMonthOutlinedIcon from "@mui/icons-material/CalendarMonthOutlined";
import CategoryOutlinedIcon from "@mui/icons-material/CategoryOutlined";
import OpenInNewRoundedIcon from "@mui/icons-material/OpenInNewRounded";
import PersonOutlineRoundedIcon from "@mui/icons-material/PersonOutlineRounded";
import TrackChangesOutlinedIcon from "@mui/icons-material/TrackChangesOutlined";

import Alert from "@mui/material/Alert";
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 CircularProgress from "@mui/material/CircularProgress";
import Divider from "@mui/material/Divider";
import Link from "@mui/material/Link";
import Paper from "@mui/material/Paper";
import Typography from "@mui/material/Typography";

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

import { useAppLanguage } from "@/components/providers/app-language-provider";

import type {
  RgcDecisionRow,
  RgcDecisionStatus,
} from "../../data/rgc-decision-data";

import {
  normalizeRgcDecisionLanguage,
  rgcDecisionText,
} from "../../data/rgc-decision-i18n";

import { useRgcDecisionList } from "../../hook/use-rgc-decision";

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 stripHtml(
  html?: string | null,
): string {
  if (!html) {
    return "";
  }

  return String(html)
    .replace(/<[^>]*>/g, " ")
    .replace(/&nbsp;/gi, " ")
    .replace(/&amp;/gi, "&")
    .replace(/&lt;/gi, "<")
    .replace(/&gt;/gi, ">")
    .replace(/&quot;/gi, '"')
    .replace(/&#39;/gi, "'")
    .replace(/\s+/g, " ")
    .trim();
}

function normalizeLogoUrl(
  value?: string | null,
): string {
  const logo =
    String(value ?? "").trim();

  if (!logo) {
    return "";
  }

  if (
    /^(https?:|data:|blob:)/i.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 StatusChip({
  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
              ? "#FF8080"
              : "#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: 26,

        color:
          styles.color,

        borderColor:
          styles.borderColor,

        bgcolor:
          styles.backgroundColor,

        borderRadius:
          "999px",

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

function MetaItem({
  icon,
  label,
  children,
}: {
  icon: ReactNode;
  label: string;
  children: ReactNode;
}) {
  const theme =
    useTheme();

  const isDark =
    theme.palette.mode ===
    "dark";

  return (
    <Box
      sx={{
        minWidth: 0,
        display: "flex",
        alignItems: "center",
        gap: 1,
      }}
    >
      <Box
        sx={{
          flexShrink: 0,
          display: "flex",
          alignItems: "center",

          color: isDark
            ? "#98A2B3"
            : "#717680",

          "& svg": {
            fontSize: 18,
          },
        }}
      >
        {icon}
      </Box>

      <Typography
        sx={{
          flexShrink: 0,

          color: isDark
            ? "#98A2B3"
            : "#717680",

          fontSize: 13,
          fontWeight: 400,
          lineHeight: "20px",
          whiteSpace: "nowrap",
        }}
      >
        {label}
      </Typography>

      <Box
        sx={{
          minWidth: 0,
          flex: 1,
        }}
      >
        {children}
      </Box>
    </Box>
  );
}

function SectionField({
  label,
  value,
  link = false,
}: {
  label: string;
  value?:
    | string
    | null;
  link?: boolean;
}) {
  const theme =
    useTheme();

  const isDark =
    theme.palette.mode ===
    "dark";

  const rawValue =
    String(
      value ?? "",
    ).trim();

  const displayValue =
    link
      ? rawValue
      : stripHtml(
          rawValue,
        );

  return (
    <Box
      sx={{
        width: "100%",
        minWidth: 0,
      }}
    >
      <Typography
        sx={{
          mb: 1,

          color: isDark
            ? "#F5F5F6"
            : "#344054",

          fontSize: 15,
          fontWeight: 600,
          lineHeight: "24px",
        }}
      >
        {label}
      </Typography>

      <Paper
        elevation={0}
        sx={{
          width: "100%",
          minWidth: 0,
          minHeight: 56,

          px: 2,
          py: 1.5,

          display: "flex",
          alignItems: "center",

          borderRadius:
            "8px",

          border:
            "1px solid",

          borderColor:
            isDark
              ? "#344054"
              : "#E4E7EC",

          bgcolor:
            isDark
              ? "#182230"
              : "#F9FAFB",
        }}
      >
        {link &&
        displayValue ? (
          <Link
            href={
              displayValue
            }
            target="_blank"
            rel="noopener noreferrer"
            underline="hover"
            sx={{
              maxWidth:
                "100%",

              display:
                "inline-flex",

              alignItems:
                "center",

              gap: 0.75,

              color:
                theme.palette
                  .primary.main,

              fontSize: 13,
              fontWeight: 500,

              overflow:
                "hidden",
            }}
          >
            <Box
              component="span"
              sx={{
                minWidth: 0,

                overflow:
                  "hidden",

                textOverflow:
                  "ellipsis",

                whiteSpace:
                  "nowrap",
              }}
            >
              {displayValue}
            </Box>

            <OpenInNewRoundedIcon
              sx={{
                flexShrink: 0,
                fontSize: 16,
              }}
            />
          </Link>
        ) : (
          <Typography
            sx={{
              width: "100%",

              color: isDark
                ? "#F5F5F6"
                : "#181D27",

              fontSize: 13,

              lineHeight:
                "20px",

              whiteSpace:
                "pre-wrap",

              overflowWrap:
                "anywhere",

              wordBreak:
                "break-word",
            }}
          >
            {displayValue ||
              "-"}
          </Typography>
        )}
      </Paper>
    </Box>
  );
}

function DetailContent({
  row,
}: {
  row: RgcDecisionRow;
}) {
  const theme =
    useTheme();

  const isDark =
    theme.palette.mode ===
    "dark";

  const {
    language,
  } =
    useAppLanguage();

  const rgcLanguage =
    normalizeRgcDecisionLanguage(
      language,
    );

  const text =
    rgcDecisionText[
      rgcLanguage
    ] ??
    rgcDecisionText.en;

  const logoUrl =
    useMemo(
      () =>
        normalizeLogoUrl(
          row.ministryLogo,
        ),
      [
        row.ministryLogo,
      ],
    );

  const [
    failedLogoUrl,
    setFailedLogoUrl,
  ] =
    useState<
      string | null
    >(null);

  const showLogo =
    Boolean(logoUrl) &&
    failedLogoUrl !==
      logoUrl;

  const verificationLink =
    row.verificationLink?.trim() ||
    row.verificationDownloadUrl?.trim() ||
    "";

  const plenaryTitle =
    row.plenary?.trim() ||
    (row.plenaryId
      ? `Plenary #${row.plenaryId}`
      : text.title);

  const valueTextSx = {
    minWidth: 0,

    color: isDark
      ? "#F5F5F6"
      : "#181D27",

    fontSize: 13,
    fontWeight: 500,
    lineHeight: "20px",

    overflow:
      "hidden",

    textOverflow:
      "ellipsis",

    whiteSpace:
      "nowrap",
  } as const;

  return (
    <Paper
      elevation={0}
      sx={{
        width: "100%",
        minWidth: 0,

        border:
          "1px solid",

        borderColor:
          theme.palette
            .divider,

        borderRadius:
          "12px",

        bgcolor:
          theme.palette
            .background.paper,

        overflow:
          "hidden",
      }}
    >
      <Box
        sx={{
          p: {
            xs: 2,
            md: 3,
          },
        }}
      >
        <Typography
          sx={{
            mb: 2,

            color:
              theme.palette
                .text.primary,

            fontSize: {
              xs: 20,
              md: 24,
            },

            fontWeight: 600,

            lineHeight: 1.3,
          }}
        >
          {plenaryTitle}
        </Typography>

        <Divider />

        <Box
          sx={{
            py: 2.5,

            display: "grid",

            gridTemplateColumns:
              {
                xs: "1fr",

                sm: "repeat(2, minmax(0, 1fr))",

                lg: "repeat(3, minmax(0, 1fr))",

                xl: "2fr 1.2fr 1.2fr 1.1fr 1.4fr",
              },

            columnGap: 3,

            rowGap: 2,

            alignItems:
              "center",
          }}
        >
          <MetaItem
            icon={
              <AccountBalanceOutlinedIcon />
            }
            label={
              text.ministry
            }
          >
            <Box
              sx={{
                minWidth: 0,

                display:
                  "flex",

                alignItems:
                  "center",

                gap: 1,
              }}
            >
              <Avatar
                src={
                  showLogo
                    ? logoUrl
                    : undefined
                }
                slotProps={{
                  img: {
                    onError:
                      () =>
                        setFailedLogoUrl(
                          logoUrl,
                        ),
                  },
                }}
                sx={{
                  width: 26,
                  height: 26,

                  border:
                    "1px solid",

                  borderColor:
                    theme.palette
                      .primary.main,

                  bgcolor:
                    alpha(
                      theme.palette
                        .primary.main,
                      0.08,
                    ),

                  color:
                    theme.palette
                      .primary.main,

                  fontSize: 10,
                  fontWeight: 700,

                  "& img": {
                    objectFit:
                      "contain",

                    p: "1px",
                  },
                }}
              >
                {!showLogo
                  ? getInitial(
                      row.ministry,
                    )
                  : null}
              </Avatar>

              <Typography
                sx={
                  valueTextSx
                }
              >
                {row.ministry ||
                  "-"}
              </Typography>
            </Box>
          </MetaItem>

          <MetaItem
            icon={
              <CalendarMonthOutlinedIcon />
            }
            label={
              text.meetingDate
            }
          >
            <Typography
              sx={
                valueTextSx
              }
            >
              {formatDate(
                row.meetingDate ||
                  row.effectiveDate,
              )}
            </Typography>
          </MetaItem>

          <MetaItem
            icon={
              <CategoryOutlinedIcon />
            }
            label={
              text.category
            }
          >
            <Typography
              sx={
                valueTextSx
              }
            >
              {row.category ||
                row.measureCategory ||
                "-"}
            </Typography>
          </MetaItem>

          <MetaItem
            icon={
              <TrackChangesOutlinedIcon />
            }
            label={
              text.status
            }
          >
            <StatusChip
              status={
                row.status
              }
            />
          </MetaItem>

          <MetaItem
            icon={
              <PersonOutlineRoundedIcon />
            }
            label={
              text.focalPerson
            }
          >
            <Typography
              sx={
                valueTextSx
              }
            >
              {row.focalPerson ||
                "-"}
            </Typography>
          </MetaItem>
        </Box>

        <Divider
          sx={{
            mb: 2.5,
          }}
        />

        <Box
          sx={{
            display: "grid",
            gap: 2,
          }}
        >
          <SectionField
            label={
              text.issueDescription
            }
            value={
              row.issueDescription
            }
          />

          <SectionField
            label={
              text.recommendations
            }
            value={
              row.recommendations
            }
          />

          <SectionField
            label={
              text.rgcDecision
            }
            value={
              row.decision
            }
          />

          <SectionField
            label={
              text.indicators
            }
            value={
              row.indicator
            }
          />

          <SectionField
            label={
              text.progressSolution
            }
            value={
              row.progressSolution
            }
          />

          <SectionField
            label={
              text.implementationChallenges
            }
            value={
              row.implementationChallenges
            }
          />

          <SectionField
            label={
              text.request
            }
            value={
              row.request
            }
          />

          <SectionField
            label={
              text.nextStep
            }
            value={
              row.nextStep
            }
          />

          <SectionField
            label={
              text.sourceOfVerification
            }
            value={
              row.sourceOfVerification
            }
          />

          <SectionField
            label={
              text.verificationLink
            }
            value={
              verificationLink
            }
            link
          />
        </Box>
      </Box>
    </Paper>
  );
}

export function CefpRgcDecisionDetailPage() {
  const theme =
    useTheme();

  const router =
    useRouter();

  const params =
    useParams<{
      id: string;
    }>();

  const {
    language,
  } =
    useAppLanguage();

  const rgcLanguage =
    normalizeRgcDecisionLanguage(
      language,
    );

  const text =
    rgcDecisionText[
      rgcLanguage
    ] ??
    rgcDecisionText.en;

  const {
    rows: rawRows,
    isLoading,
    error,
    reload,
  } =
    useRgcDecisionList();

  const rows =
    useMemo<
      RgcDecisionRow[]
    >(
      () =>
        Array.isArray(
          rawRows,
        )
          ? (rawRows as RgcDecisionRow[])
          : [],
      [rawRows],
    );

  const decisionId =
    Number(
      params?.id,
    );

  const row =
    useMemo<
      RgcDecisionRow | null
    >(
      () => {
        if (
          !Number.isInteger(
            decisionId,
          ) ||
          decisionId <= 0
        ) {
          return null;
        }

        return (
          rows.find(
            (
              item: RgcDecisionRow,
            ) =>
              item.id ===
              decisionId,
          ) ?? null
        );
      },
      [
        decisionId,
        rows,
      ],
    );

  return (
    <Box
      sx={{
        width: "100%",

        minHeight:
          "calc(100dvh - 64px)",

        bgcolor:
          theme.palette
            .background.default,

        px: {
          xs: 2,
          md: 3,
        },

        py: {
          xs: 2,
          md: 2.5,
        },
      }}
    >
      <Box
        sx={{
          mb: 3,

          display:
            "flex",

          alignItems:
            "flex-start",

          gap: 2,
        }}
      >
        <Button
          type="button"
          variant="text"
          startIcon={
            <ArrowBackIosNewRoundedIcon
              sx={{
                fontSize:
                  "12px !important",
              }}
            />
          }
          onClick={() =>
            router.push(
              "/cefp/rgc-decision",
            )
          }
          sx={{
            minWidth: 0,

            px: 0,

            color:
              theme.palette
                .text.secondary,

            fontSize: 12,

            fontWeight: 500,

            textTransform:
              "none",
          }}
        >
          {text.back}
        </Button>

        <Box>
          <Typography
            component="h1"
            sx={{
              color:
                theme.palette
                  .text.primary,

              fontSize: {
                xs: 20,
                md: 24,
              },

              fontWeight: 700,

              lineHeight: 1.25,
            }}
          >
            {text.detailTitle}
          </Typography>

          <Typography
            sx={{
              mt: 0.5,

              color:
                theme.palette
                  .text.secondary,

              fontSize: 12,
            }}
          >
            {text.detailDescription}
          </Typography>
        </Box>
      </Box>

      {isLoading ? (
        <Paper
          elevation={0}
          sx={{
            minHeight:
              360,

            display:
              "flex",

            alignItems:
              "center",

            justifyContent:
              "center",

            border:
              "1px solid",

            borderColor:
              theme.palette
                .divider,

            borderRadius:
              "12px",
          }}
        >
          <CircularProgress
            size={32}
          />
        </Paper>
      ) : error ? (
        <Alert
          severity="error"
          action={
            <Button
              color="inherit"
              size="small"
              onClick={() =>
                void reload()
              }
            >
              {text.reload}
            </Button>
          }
        >
          {error}
        </Alert>
      ) : row ? (
        <DetailContent
          row={row}
        />
      ) : (
        <Alert
          severity="warning"
        >
          {text.notFound}
        </Alert>
      )}
    </Box>
  );
}

export default CefpRgcDecisionDetailPage;