"use client";

import { useMemo, useState, type ReactNode } from "react";
import { useParams, useRouter } from "next/navigation";

import ArrowBackIosNewRoundedIcon from "@mui/icons-material/ArrowBackIosNewRounded";
import AccountBalanceOutlinedIcon from "@mui/icons-material/AccountBalanceOutlined";
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 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;

  return `${match[1]}-${match[2]}-${match[3]}`;
}

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

  const style =
    status === "Solved"
      ? {
          color: isDark ? "#4ADE80" : "#16A34A",
          border: "#86EFAC",
          background: isDark
            ? alpha("#22C55E", 0.12)
            : "#F0FDF4",
        }
      : status === "In Progress"
        ? {
            color: isDark ? "#FBBF24" : "#D97706",
            border: "#FCD34D",
            background: isDark
              ? alpha("#F59E0B", 0.12)
              : "#FFF8E8",
          }
        : {
            color: isDark ? "#FF8080" : "#EF4444",
            border: "#FCA5A5",
            background: isDark
              ? alpha("#EF4444", 0.13)
              : "#FEF2F2",
          };

  return (
    <Chip
      label={status}
      size="small"
      variant="outlined"
      sx={{
        height: 24,
        maxWidth: "100%",
        borderRadius: "999px",
        borderColor: style.border,
        bgcolor: style.background,
        color: style.color,

        "& .MuiChip-label": {
          px: 1.25,
          fontSize: 11,
          fontWeight: 600,
          overflow: "hidden",
          textOverflow: "ellipsis",
        },
      }}
    />
  );
}

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 displayValue = String(value ?? "").trim();

  return (
    <Box
      sx={{
        width: "100%",
        minWidth: 0,
      }}
    >
      <Typography
        sx={{
          mb: 1,
          color: isDark ? "#F5F5F6" : "#344054",
          fontSize: 16,
          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",

          overflow: "hidden",
          borderRadius: "8px",
          border: "1px solid",
          borderColor: isDark ? "#344054" : "#E4E7EC",

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

              display: "inline-flex",
              alignItems: "center",
              gap: 0.75,

              color: isDark ? "#F5F5F6" : "#181D27",
              fontSize: 13,
              fontWeight: 400,
              lineHeight: "20px",

              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}
          >
            <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%",
              minWidth: 0,

              color: isDark ? "#F5F5F6" : "#181D27",
              fontSize: 13,
              fontWeight: 400,
              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 logoUrl = useMemo(
    () => normalizeLogoUrl(row.ministryLogo),
    [row.ministryLogo],
  );

  const [logoFailed, setLogoFailed] = useState(false);

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

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

  const valueTextSx = {
    minWidth: 0,
    color: isDark ? "#F5F5F6" : "#181D27",
    fontSize: 13,
    fontWeight: 500,
    lineHeight: "20px",
    overflow: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
  } as const;

  return (
    <Box
      sx={{
        width: "100%",
        minWidth: 0,
      }}
    >
      <Typography
        sx={{
          mb: 2,
          color: isDark ? "#F9FAFB" : "#181D27",
          fontSize: {
            xs: 20,
            md: 24,
          },
          fontWeight: 600,
          lineHeight: 1,
          letterSpacing: 0,
        }}
      >
        {plenaryTitle}
      </Typography>

      <Divider />

      <Box
        sx={{
          py: 2,

          display: "grid",
          gridTemplateColumns: {
            xs: "1fr",
            sm: "repeat(2, minmax(0, 1fr))",
            lg: "repeat(3, minmax(0, 1fr))",
            xl: "2.2fr 1.15fr 1fr 1fr 1.2fr",
          },

          columnGap: 3,
          rowGap: 2,
          alignItems: "center",
        }}
      >
        <MetaItem
          icon={<AccountBalanceOutlinedIcon />}
          label="Ministry"
        >
          <Box
            sx={{
              minWidth: 0,
              display: "flex",
              alignItems: "center",
              gap: 1,
            }}
          >
            <Avatar
              src={!logoFailed && logoUrl ? logoUrl : undefined}
              slotProps={{
                img: {
                  onError: () => setLogoFailed(true),
                },
              }}
              sx={{
                width: 24,
                height: 24,
                flexShrink: 0,

                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",
                },
              }}
            >
              {!logoUrl || logoFailed
                ? getInitial(row.ministry)
                : null}
            </Avatar>

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

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

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

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

        <MetaItem
          icon={<PersonOutlineRoundedIcon />}
          label="Focal Person (H.E)"
        >
          <Typography
            title={row.focalPerson || "-"}
            sx={valueTextSx}
          >
            {row.focalPerson || "-"}
          </Typography>
        </MetaItem>
      </Box>

      <Divider sx={{ mb: 2 }} />

      <Box
        sx={{
          width: "100%",
          minWidth: 0,

          display: "grid",
          gap: 2,
        }}
      >
        <SectionField
          label="Issues Description"
          value={row.issueDescription}
        />

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

        <SectionField
          label="RGC Decision"
          value={row.decision}
        />

        <SectionField
          label="Indicators"
          value={row.indicator}
        />

        <SectionField
          label="Progress Solution"
          value={row.progressSolution}
        />

        <SectionField
          label="Implementation Challenges"
          value={row.implementationChallenges}
        />

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

        <SectionField
          label="Next Step"
          value={row.nextStep}
        />

        <SectionField
          label="Source of Verification"
          value={row.sourceOfVerification}
        />

        <SectionField
          label="Link to Verification Source"
          value={verificationLink}
          link
        />
      </Box>
    </Box>
  );
}

export function CdcRgcDecisionDetailPage() {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const router = useRouter();

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

  const { language } = useAppLanguage();

  const rgcLanguage =
    normalizeRgcDecisionLanguage(language);

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

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

  const decisionId = Number(params?.id);

  const row = useMemo(
    () =>
      Number.isInteger(decisionId) &&
      decisionId > 0
        ? rows.find(
            (item) => item.id === decisionId,
          ) ?? null
        : null,
    [decisionId, rows],
  );

  return (
    <Box
      sx={{
        width: "100%",
        minWidth: 0,
        minHeight: "calc(100dvh - 64px)",

        overflowX: "hidden",

        bgcolor: theme.palette.background.default,

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

        py: {
          xs: 2,
          md: 2.25,
        },
      }}
    >
      <Box
        sx={{
          width: "100%",
          minWidth: 0,
          mb: 3,

          display: "grid",

          gridTemplateColumns: {
            xs: "1fr",
            sm: "72px minmax(0, 1fr)",
          },

          columnGap: {
            xs: 0,
            sm: 2,
          },

          rowGap: 1.25,
          alignItems: "start",
        }}
      >
        <Button
          variant="text"
          startIcon={
            <ArrowBackIosNewRoundedIcon
              sx={{
                fontSize: "12px !important",
              }}
            />
          }
          onClick={() =>
            router.push("/cdc/rgc-decision")
          }
          sx={{
            minWidth: 0,
            width: "fit-content",
            mt: 0.1,
            px: 0,

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

            textTransform: "none",
            fontSize: 12,
            fontWeight: 500,

            "& .MuiButton-startIcon": {
              mr: 0.75,
            },
          }}
        >
          Back
        </Button>

        <Box sx={{ minWidth: 0 }}>
          <Typography
            component="h1"
            sx={{
              color: isDark ? "#F9FAFB" : "#181D27",
              fontSize: {
                xs: 18,
                md: 20,
              },
              fontWeight: 600,
              lineHeight: 1.25,
              letterSpacing: 0,
            }}
          >
            RGC Decision Detail
          </Typography>

          <Typography
            sx={{
              mt: 0.5,
              color: isDark ? "#98A2B3" : "#717680",
              fontSize: 12,
              fontWeight: 400,
              lineHeight: 1.5,
            }}
          >
            Detail information of RGC Decision
          </Typography>
        </Box>
      </Box>

      <Box
        sx={{
          width: "100%",
          minWidth: 0,
        }}
      >
        {isLoading ? (
          <Paper
            elevation={0}
            sx={{
              minHeight: 360,

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

              borderRadius: 2,
              border: `1px solid ${theme.palette.divider}`,
            }}
          >
            <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">
            RGC Decision not found.
          </Alert>
        )}
      </Box>
    </Box>
  );
}

export default CdcRgcDecisionDetailPage;