"use client";

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

import Alert from "@mui/material/Alert";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import Paper from "@mui/material/Paper";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";
import type { GridPaginationModel } from "@mui/x-data-grid";

import { translateIssueMatrixValue } from "@/features/pswg/issue-matrix/components/issue-matrix-i18n";
import { StatusBadge } from "@/features/pswg/working-group-issues/components/table/wg-issues-table-cells";
import { WG_ISSUES_PAGE_SIZE } from "@/features/pswg/working-group-issues/components/table/wg-issues-table-config";
import { WgIssuesTableFooter } from "@/features/pswg/working-group-issues/components/table/wg-issues-table-footer";
import type { IssueStatus } from "@/features/pswg/working-group-issues/wg-issues-data";
import type { WgIssuesLanguage } from "@/features/pswg/working-group-issues/wg-issues-i18n";

import type { CdcIssueMatrixRow } from "./cdc-issue-matrix-data";
import { CdcIssueMatrixActionCell } from "./cdc-issue-matrix-table-cells";
import {
  cdcIssueMatrixText,
  type IssueMatrixLanguage,
} from "./cdc-issue-matrix-i18n";

const LEFT_META_LABEL_WIDTH = 88;
const RIGHT_META_LABEL_WIDTH = 150;
const GRID_VALUE_LEADING_SLOT_WIDTH = 24;

type CdcIssueMatrixGridProps = {
  rows: CdcIssueMatrixRow[];
  language: IssueMatrixLanguage;
  loading?: boolean;
  error?: string | null;
  onEdit?: (row: CdcIssueMatrixRow) => void;
  onRemove?: (row: CdcIssueMatrixRow) => void;
};

function toWgIssuesLanguage(language: IssueMatrixLanguage): WgIssuesLanguage {
  return language === "kh" ? "km" : "en";
}

function GridLabel({ children }: { children: ReactNode }) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Typography
      sx={{
        color: isDark ? alpha("#ffffff", 0.6) : "#717680",
        fontSize: 12,
        fontWeight: 500,
        whiteSpace: "nowrap",
      }}
    >
      {children}
    </Typography>
  );
}

function GridMetaRow({
  children,
  label,
  labelWidth,
}: {
  children: ReactNode;
  label: string;
  labelWidth: number;
}) {
  return (
    <Box
      sx={{
        display: "grid",
        gridTemplateColumns: `${labelWidth}px minmax(0, 1fr)`,
        alignItems: "center",
        columnGap: 1.5,
        minHeight: 27,
        width: "100%",
        minWidth: 0,
      }}
    >
      <GridLabel>{label}</GridLabel>
      <Box sx={{ minWidth: 0 }}>{children}</Box>
    </Box>
  );
}

function GridValueSlot({
  children,
  leading,
}: {
  children: ReactNode;
  leading?: ReactNode;
}) {
  if (!leading) {
    return <Box sx={{ minWidth: 0 }}>{children}</Box>;
  }

  return (
    <Box
      sx={{
        display: "grid",
        gridTemplateColumns: `${GRID_VALUE_LEADING_SLOT_WIDTH}px minmax(0, 1fr)`,
        columnGap: 1.25,
        alignItems: "center",
        width: "100%",
        minWidth: 0,
      }}
    >
      <Box
        sx={{
          width: GRID_VALUE_LEADING_SLOT_WIDTH,
          height: GRID_VALUE_LEADING_SLOT_WIDTH,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          flexShrink: 0,
        }}
      >
        {leading}
      </Box>
      <Box sx={{ minWidth: 0 }}>{children}</Box>
    </Box>
  );
}

function GridValueText({
  children,
  clamp = false,
  wrap = false,
}: {
  children: ReactNode;
  clamp?: boolean;
  wrap?: boolean;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Typography
      sx={{
        color: isDark ? "#ffffff" : "#252b37",
        fontSize: 12,
        fontWeight: 500,
        lineHeight: 1.5,
        ...(wrap
          ? {
              whiteSpace: "normal",
              wordBreak: "break-word",
            }
          : { whiteSpace: "nowrap" }),
        ...(clamp
          ? {
              display: "-webkit-box",
              WebkitLineClamp: 4,
              WebkitBoxOrient: "vertical",
              overflow: "hidden",
              whiteSpace: "normal",
            }
          : {}),
      }}
    >
      {children}
    </Typography>
  );
}

function GridMinistryAvatar({
  image,
  name,
}: {
  image: string | null;
  name: string;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Avatar
      src={image ?? undefined}
      alt={name}
      sx={{
        width: GRID_VALUE_LEADING_SLOT_WIDTH,
        height: GRID_VALUE_LEADING_SLOT_WIDTH,
        bgcolor: isDark ? "#1f2937" : "#eef4ff",
        color: isDark ? "#ffffff" : "#175cd3",
        fontSize: 11,
        fontWeight: 700,
      }}
    >
      {name.charAt(0)}
    </Avatar>
  );
}

function GridContentBlock({
  label,
  text,
}: {
  label: string;
  text: string;
}) {
  return (
    <Box sx={{ minWidth: 0 }}>
      <GridLabel>{label}</GridLabel>
      <Box sx={{ mt: 0.75 }}>
        <GridValueText clamp>{text || "-"}</GridValueText>
      </Box>
    </Box>
  );
}

function CdcIssueMatrixGridCard({
  language,
  row,
  onEdit,
  onRemove,
}: {
  language: IssueMatrixLanguage;
  row: CdcIssueMatrixRow;
  onEdit?: (row: CdcIssueMatrixRow) => void;
  onRemove?: (row: CdcIssueMatrixRow) => void;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const text = cdcIssueMatrixText[language] ?? cdcIssueMatrixText.en;
  const labels = text.gridCard;
  const wgLanguage = toWgIssuesLanguage(language);

  const category = translateIssueMatrixValue(row.category, language);
  const issue = translateIssueMatrixValue(row.issue, language);
  const issueDescription = translateIssueMatrixValue(
    row.issueDescription,
    language,
  );
  const recommendation = translateIssueMatrixValue(row.recommendation, language);
  const rgcDecision = translateIssueMatrixValue(
    row.governmentDecision,
    language,
  );
  const remark = translateIssueMatrixValue(row.remark ?? "-", language);
  const escalation = row.plenaryEscalation
    ? labels.plenary
    : labels.notPlenary;

  return (
    <Paper
      elevation={0}
      sx={{
        borderRadius: "12px",
        border: `1px solid ${isDark ? alpha("#ffffff", 0.1) : "#f5f5f5"}`,
        bgcolor: isDark ? "#111827" : "#ffffff",
        px: { xs: 2, md: 2.5 },
        py: { xs: 2, md: 2.25 },
      }}
    >
      <Box
        sx={{
          display: "flex",
          alignItems: "flex-start",
          justifyContent: "space-between",
          gap: 2,
        }}
      >
        <Typography
          sx={{
            color: isDark ? "#ffffff" : "#252b37",
            fontSize: 15,
            fontWeight: 600,
            lineHeight: 1.4,
            minWidth: 0,
          }}
        >
          {translateIssueMatrixValue(row.workingGroup, language)}
        </Typography>

        <CdcIssueMatrixActionCell
          row={row}
          language={language}
          onEdit={onEdit}
          onRemove={onRemove}
        />
      </Box>

      <Box
        sx={{
          mt: 2.25,
          display: "grid",
          gridTemplateColumns: { xs: "1fr", md: "minmax(0, 1fr) minmax(0, 1fr)" },
          columnGap: { xs: 2, md: 4, lg: 5 },
          rowGap: 2.25,
          alignItems: "start",
        }}
      >
        <Box sx={{ display: "flex", flexDirection: "column", gap: 2, minWidth: 0 }}>
          <GridMetaRow label={`${labels.no} :`} labelWidth={LEFT_META_LABEL_WIDTH}>
            <GridValueSlot>
              <GridValueText>{row.id}</GridValueText>
            </GridValueSlot>
          </GridMetaRow>

          <GridMetaRow
            label={`${labels.ministry} :`}
            labelWidth={LEFT_META_LABEL_WIDTH}
          >
            <GridValueSlot
              leading={
                row.primaryAgency && row.primaryAgency !== "-" ? (
                  <GridMinistryAvatar
                    image={row.primaryAgencyImage}
                    name={row.primaryAgency}
                  />
                ) : undefined
              }
            >
              <GridValueText>
                {row.primaryAgency && row.primaryAgency !== "-"
                  ? row.primaryAgency
                  : "-"}
              </GridValueText>
            </GridValueSlot>
          </GridMetaRow>

          <GridMetaRow label={`${labels.status} :`} labelWidth={LEFT_META_LABEL_WIDTH}>
            <GridValueSlot>
              <StatusBadge
                status={row.status as IssueStatus}
                language={wgLanguage}
              />
            </GridValueSlot>
          </GridMetaRow>
        </Box>

        <Box sx={{ display: "flex", flexDirection: "column", gap: 2, minWidth: 0 }}>
          <GridMetaRow
            label={`${labels.categoryOfIssue}:`}
            labelWidth={RIGHT_META_LABEL_WIDTH}
          >
            <GridValueSlot>
              <GridValueText>{category}</GridValueText>
            </GridValueSlot>
          </GridMetaRow>

          <GridMetaRow
            label={`${labels.issue} :`}
            labelWidth={RIGHT_META_LABEL_WIDTH}
          >
            <GridValueSlot>
              <GridValueText wrap>{issue}</GridValueText>
            </GridValueSlot>
          </GridMetaRow>

          <GridMetaRow
            label={`${labels.escalation} :`}
            labelWidth={RIGHT_META_LABEL_WIDTH}
          >
            <GridValueSlot>
              <GridValueText>{escalation}</GridValueText>
            </GridValueSlot>
          </GridMetaRow>
        </Box>
      </Box>

      <Box
        sx={{
          mt: 2.25,
          display: "grid",
          gridTemplateColumns: { xs: "1fr", md: "minmax(0, 1fr) minmax(0, 1fr)" },
          columnGap: { xs: 2, md: 4, lg: 5 },
          rowGap: 2.25,
          alignItems: "start",
        }}
      >
        <Box sx={{ display: "flex", flexDirection: "column", gap: 2.75 }}>
          <GridContentBlock
            label={labels.issueDescription}
            text={issueDescription}
          />
          <GridContentBlock
            label={labels.recommendation}
            text={recommendation}
          />
        </Box>

        <Box sx={{ display: "flex", flexDirection: "column", gap: 2.75 }}>
          <GridContentBlock label={labels.rgcDecision} text={rgcDecision} />
          <GridContentBlock label={labels.remark} text={remark} />
        </Box>
      </Box>
    </Paper>
  );
}

export function CdcIssueMatrixGrid({
  rows,
  language,
  loading = false,
  error = null,
  onEdit,
  onRemove,
}: CdcIssueMatrixGridProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const text = cdcIssueMatrixText[language] ?? cdcIssueMatrixText.en;
  const wgLanguage = toWgIssuesLanguage(language);
  const [paginationModel, setPaginationModel] = useState<GridPaginationModel>({
    page: 0,
    pageSize: WG_ISSUES_PAGE_SIZE,
  });

  const pageCount = Math.max(
    1,
    Math.ceil(rows.length / paginationModel.pageSize),
  );
  const currentPage = Math.min(paginationModel.page, pageCount - 1);

  const paginatedRows = useMemo(() => {
    const start = currentPage * paginationModel.pageSize;
    const end = start + paginationModel.pageSize;

    return rows.slice(start, end);
  }, [currentPage, paginationModel.pageSize, rows]);

  const footer = (
    <WgIssuesTableFooter
      language={wgLanguage}
      page={currentPage}
      pageCount={pageCount}
      onPrevious={() =>
        setPaginationModel((current) => ({
          ...current,
          page: Math.max(0, current.page - 1),
        }))
      }
      onNext={() =>
        setPaginationModel((current) => ({
          ...current,
          page: Math.min(pageCount - 1, current.page + 1),
        }))
      }
      onSelectPage={(pageIndex) =>
        setPaginationModel((current) => ({
          ...current,
          page: pageIndex,
        }))
      }
    />
  );

  if (error) {
    return (
      <Alert severity="error" sx={{ borderRadius: 2 }}>
        {error}
      </Alert>
    );
  }

  if (!loading && rows.length === 0) {
    return (
      <Paper
        elevation={0}
        sx={{
          borderRadius: "12px",
          border: `1px solid ${isDark ? alpha("#ffffff", 0.12) : "#e9eaeb"}`,
          bgcolor: isDark ? "#111827" : "#ffffff",
          px: 3,
          py: 6,
          textAlign: "center",
        }}
      >
        <Typography sx={{ color: theme.palette.text.secondary, fontSize: 14 }}>
          {text.noData}
        </Typography>
      </Paper>
    );
  }

  return (
    <Box>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          gap: 2.5,
        }}
      >
        {paginatedRows.map((row) => (
          <CdcIssueMatrixGridCard
            key={row.id}
            language={language}
            row={row}
            onEdit={onEdit}
            onRemove={onRemove}
          />
        ))}
      </Box>

      <Paper
        elevation={0}
        sx={{
          mt: 2,
          borderRadius: "12px",
          border: `1px solid ${isDark ? alpha("#ffffff", 0.12) : "#e9eaeb"}`,
          overflow: "hidden",
          bgcolor: isDark ? "#111827" : "#ffffff",
        }}
      >
        {footer}
      </Paper>
    </Box>
  );
}
