"use client";

import { useMemo, useState } from "react";

import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Tooltip from "@mui/material/Tooltip";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";
import type { GridColDef } from "@mui/x-data-grid";

import { DataTable, DataTableNumberCell } from "@/components/ui/data-table";
import { IssueStatusBadge } from "@/components/ui/issue-status-badge";
import {
  MeetingRequestIssueDetailDialog,
  type MeetingRequestIssueDetail,
} from "@/features/ministry/meeting-request/components/view-detail/meeting-request-detail-table";
import { mapMeetingCalendarIssues, resolveMeetingAssetUrl } from "../meeting-calendar-data";
import type {
  MeetingRequest,
  MeetingRequestGovernmentAgency,
  MeetingRequestIssue,
} from "@/features/ministry/meeting-request/meeting-request-data";
import { useMeetingRequestI18n } from "@/features/ministry/meeting-request/use-meeting-request-i18n";

type MeetingCreateIssueRow = MeetingRequestIssueDetail;

const ISSUE_TABLE_ROW_HEIGHT = 60;
const ISSUE_TABLE_HEADER_HEIGHT = 50;

type MeetingCreateIssuesSectionProps = {
  issues: MeetingRequestIssue[];
  governmentAgencies?: MeetingRequestGovernmentAgency[];
  meetingRequest?: Pick<
    MeetingRequest,
    | "requestedBy"
    | "requestedDate"
    | "documentName"
    | "privateSectorWG"
    | "submittedBy"
  >;
};

function normalizeIssues(
  issues: MeetingRequestIssue[],
  governmentAgencies: MeetingRequestGovernmentAgency[],
): MeetingCreateIssueRow[] {
  return mapMeetingCalendarIssues(issues, governmentAgencies).map((item, index) => ({
    id: item.id ?? index + 1,
    issue: item.issue ?? item.title ?? "-",
    category: item.category ?? "-",
    description: item.description ?? "-",
    recommendation: item.recommendation ?? "-",
    attachment: item.attachment ?? null,
    primaryAgency: item.primaryAgency ?? "-",
    primaryAgencyLogo: item.primaryAgencyLogo ?? null,
    secondAgency: item.secondAgency ?? "Not Uploaded",
    secondAgencyLogo: item.secondAgencyLogo ?? null,
    thirdAgency: item.thirdAgency ?? "Not Uploaded",
    thirdAgencyLogo: item.thirdAgencyLogo ?? null,
    fourthAgency: item.fourthAgency ?? "Not Uploaded",
    fourthAgencyLogo: item.fourthAgencyLogo ?? null,
    fifthAgency: item.fifthAgency ?? "Not Uploaded",
    fifthAgencyLogo: item.fifthAgencyLogo ?? null,
    status: item.status ?? "Not Addressed",
  }));
}

function IssueTextCell({
  value,
  align = "left",
  bold = false,
  color,
}: {
  value: string;
  align?: "left" | "center" | "right";
  bold?: boolean;
  color: string;
}) {
  return (
    <Typography
      sx={{
        width: "100%",
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap",
        color,
        fontSize: 12,
        fontWeight: bold ? 500 : 400,
        textAlign: align,
      }}
    >
      {value}
    </Typography>
  );
}

function IssueLongTextCell({ value, color }: { value: string; color: string }) {
  return (
    <Tooltip title={value} arrow placement="top">
      <Typography
        sx={{
          width: "100%",
          overflow: "hidden",
          textOverflow: "ellipsis",
          whiteSpace: "nowrap",
          color,
          fontSize: 12,
          fontWeight: 400,
          cursor: "default",
        }}
      >
        {value}
      </Typography>
    </Tooltip>
  );
}

function AgencyCell({
  value,
  logo,
  logoByName,
  color,
  emptyLabel,
}: {
  value: string;
  logo?: string | null;
  logoByName?: Map<string, string | null>;
  color: string;
  emptyLabel: string;
}) {
  if (!value || value === "-" || value === "Not Uploaded") {
    return (
      <Typography sx={{ fontSize: 12, fontWeight: 400, color }}>
        {value === "Not Uploaded" ? emptyLabel : value || "-"}
      </Typography>
    );
  }

  const resolvedLogo = resolveMeetingAssetUrl(
    logo ?? logoByName?.get(value) ?? null,
  );

  return (
    <Box sx={{ display: "flex", alignItems: "center", gap: 1, minWidth: 0 }}>
      {resolvedLogo ? (
        <Box
          component="img"
          src={resolvedLogo}
          alt={value}
          sx={{
            width: 24,
            height: 24,
            borderRadius: "50%",
            objectFit: "cover",
            flexShrink: 0,
          }}
        />
      ) : null}

      <Typography
        sx={{
          fontSize: 12,
          fontWeight: 400,
          color,
          overflow: "hidden",
          textOverflow: "ellipsis",
          whiteSpace: "nowrap",
        }}
      >
        {value}
      </Typography>
    </Box>
  );
}

export function MeetingCreateIssuesSection({
  issues,
  governmentAgencies = [],
  meetingRequest,
}: MeetingCreateIssuesSectionProps) {
  const theme = useTheme();
  const { lang, t } = useMeetingRequestI18n();
  const labels = t.detail;
  const emptyAgencyLabel = t.meetingCalendar.issueTable.notUploaded;
  const statusLabels = t.statusLabels as Record<string, string>;
  const isDark = theme.palette.mode === "dark";
  const [selectedIssue, setSelectedIssue] =
    useState<MeetingRequestIssueDetail | null>(null);

  const textColor = isDark ? "#E5E7EB" : "#181D27";
  const mutedColor = isDark ? "#CBD5E1" : "#717680";
  const borderColor = isDark ? "#243244" : "#F5F5F5";
  const headerBg = isDark ? "#29415F" : "#DDEDFB";
  const cardBg = isDark ? "#0F172A" : "#FFFFFF";

  const rows = useMemo(
    () => normalizeIssues(issues, governmentAgencies),
    [governmentAgencies, issues],
  );

  const agencyLogoByName = useMemo(() => {
    const logos = new Map<string, string | null>();

    for (const agency of governmentAgencies) {
      if (agency.name) {
        logos.set(agency.name, agency.logo ?? null);
      }
    }

    return logos;
  }, [governmentAgencies]);

  const columns = useMemo<GridColDef<MeetingCreateIssueRow>[]>(
    () => [
      {
        field: "id",
        headerName: labels.no,
        width: 64,
        minWidth: 64,
        align: "center",
        headerAlign: "center",
        sortable: false,
        filterable: false,
        disableColumnMenu: true,
        renderCell: (params) => (
          <DataTableNumberCell
            value={
              params.api.getRowIndexRelativeToVisibleRows(params.row.id) + 1
            }
          />
        ),
      },
      {
        field: "issue",
        headerName: labels.issue,
        width: 260,
        minWidth: 220,
        renderCell: (params) => (
          <IssueTextCell value={params.row.issue} bold color={textColor} />
        ),
      },
      {
        field: "category",
        headerName: labels.categoryOfIssue,
        width: 210,
        minWidth: 190,
        renderCell: (params) => (
          <IssueTextCell value={params.row.category} color={textColor} />
        ),
      },
      {
        field: "description",
        headerName: labels.issueDescription,
        width: 320,
        minWidth: 260,
        renderCell: (params) => (
          <IssueLongTextCell value={params.row.description} color={textColor} />
        ),
      },
      {
        field: "recommendation",
        headerName: labels.recommendation,
        width: 320,
        minWidth: 260,
        renderCell: (params) => (
          <IssueLongTextCell
            value={params.row.recommendation}
            color={textColor}
          />
        ),
      },
      {
        field: "primaryAgency",
        headerName: labels.govtPrimaryAgency,
        width: 210,
        minWidth: 190,
        renderCell: (params) => (
          <AgencyCell
            value={params.row.primaryAgency}
            logo={params.row.primaryAgencyLogo}
            logoByName={agencyLogoByName}
            color={textColor}
            emptyLabel={emptyAgencyLabel}
          />
        ),
      },
      {
        field: "secondAgency",
        headerName: labels.govtSecondAgency,
        width: 210,
        minWidth: 190,
        renderCell: (params) => (
          <AgencyCell
            value={params.row.secondAgency}
            logo={params.row.secondAgencyLogo}
            logoByName={agencyLogoByName}
            color={textColor}
            emptyLabel={emptyAgencyLabel}
          />
        ),
      },
      {
        field: "thirdAgency",
        headerName: labels.govtThirdAgency,
        width: 210,
        minWidth: 190,
        renderCell: (params) => (
          <AgencyCell
            value={params.row.thirdAgency}
            logo={params.row.thirdAgencyLogo}
            logoByName={agencyLogoByName}
            color={textColor}
            emptyLabel={emptyAgencyLabel}
          />
        ),
      },
      {
        field: "fourthAgency",
        headerName: labels.govtFourthAgency,
        width: 210,
        minWidth: 190,
        renderCell: (params) => (
          <AgencyCell
            value={params.row.fourthAgency}
            logo={params.row.fourthAgencyLogo}
            logoByName={agencyLogoByName}
            color={textColor}
            emptyLabel={emptyAgencyLabel}
          />
        ),
      },
      {
        field: "fifthAgency",
        headerName: labels.govtFifthAgency,
        width: 210,
        minWidth: 190,
        renderCell: (params) => (
          <AgencyCell
            value={params.row.fifthAgency}
            logo={params.row.fifthAgencyLogo}
            logoByName={agencyLogoByName}
            color={textColor}
            emptyLabel={emptyAgencyLabel}
          />
        ),
      },
      {
        field: "status",
        headerName: labels.status,
        width: 170,
        minWidth: 150,
        align: "center",
        renderCell: (params) => (
          <IssueStatusBadge
            status={params.row.status}
            label={statusLabels[params.row.status] ?? params.row.status}
          />
        ),
      },
      {
        field: "action",
        headerName: labels.action,
        width: 140,
        minWidth: 140,
        align: "center",
        headerAlign: "center",
        sortable: false,
        filterable: false,
        disableColumnMenu: true,
        renderCell: (params) => (
          <Button
            startIcon={<VisibilityOutlinedIcon sx={{ fontSize: 18 }} />}
            onClick={(event) => {
              event.stopPropagation();
              setSelectedIssue(params.row);
            }}
            sx={{
              minWidth: 0,
              color: mutedColor,
              textTransform: "none",
              fontSize: 12,
              fontWeight: 400,
              whiteSpace: "nowrap",
              "& .MuiButton-startIcon": {
                mr: 0.5,
              },
            }}
          >
            {labels.viewDetail}
          </Button>
        ),
      },
    ],
    [agencyLogoByName, emptyAgencyLabel, labels, mutedColor, statusLabels, textColor],
  );

  const tableHeight =
    ISSUE_TABLE_HEADER_HEIGHT +
    Math.max(rows.length, 1) * ISSUE_TABLE_ROW_HEIGHT;

  return (
    <Box sx={{ width: "100%", minWidth: 0 }}>
      <DataTable
        rows={rows}
        columns={columns}
        getRowId={(row) => row.id}
        emptyMessage={labels.noIssuesFound}
        height={tableHeight}
        hidePagination
        rowHeight={ISSUE_TABLE_ROW_HEIGHT}
        columnHeaderHeight={ISSUE_TABLE_HEADER_HEIGHT}
        enableColumnMenu
        paperSx={{
          borderRadius: "6px",
          border: `1px solid ${borderColor}`,
          bgcolor: cardBg,
          backgroundImage: "none",
        }}
        dataGridSx={{
          bgcolor: cardBg,
          backgroundImage: "none",
          "& .MuiDataGrid-columnHeaders": {
            bgcolor: headerBg,
            borderBottom: `1px solid ${borderColor}`,
          },
          "& .MuiDataGrid-columnHeader": {
            px: 2,
            bgcolor: headerBg,
          },
          "& .MuiDataGrid-columnHeaderTitle": {
            color: mutedColor,
            fontSize: 12,
            fontWeight: 500,
            whiteSpace: "nowrap",
          },
          "& .MuiDataGrid-cell": {
            px: 2,
            color: textColor,
            bgcolor: cardBg,
            borderColor,
          },
          "& .MuiDataGrid-row": {
            bgcolor: cardBg,
          },
          "& .MuiDataGrid-row:hover": {
            bgcolor: isDark ? alpha("#ffffff", 0.04) : "#f9fafb",
          },
          "& .MuiDataGrid-withBorderColor": {
            borderColor,
          },
          "& .MuiDataGrid-main": {
            overflow: "hidden",
          },
          "& .MuiDataGrid-virtualScroller": {
            overflowX: "auto !important",
            overflowY: "auto !important",
            bgcolor: cardBg,
          },
        }}
      />

      <MeetingRequestIssueDetailDialog
        open={Boolean(selectedIssue)}
        issue={selectedIssue}
        meetingRequest={
          meetingRequest ?? {
            requestedBy: "-",
            requestedDate: "-",
            documentName: "-",
          }
        }
        agencyLogoByName={agencyLogoByName}
        labels={labels}
        language={lang}
        statusLabels={statusLabels}
        onClose={() => setSelectedIssue(null)}
        dialogZIndex={1700}
      />
    </Box>
  );
}
