"use client";

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

import MoreVertIcon from "@mui/icons-material/MoreVert";
import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";
import type { SxProps, Theme } from "@mui/material/styles";

import {
  DataTable,
  DataTableNumberCell,
  type DataTableColDef,
} from "@/components/ui/data-table";
import { useAppLanguage } from "@/components/providers/app-language-provider";
import { ExportCommentIcon, EyeViewIcon } from "@/components/ui/icon";
import { PdfDocumentIcon } from "@/components/ui/pdf-document-icon";
import {
  getDisplayFileName,
  getDocumentUrl,
  type UploadedFileMetadata,
} from "@/lib/document-file";
import { formatNumber } from "@/lib/number-utils";

import type { ProgressReportMinistryRow } from "../../progress-report-detail-data";
import type { ProgressReportDetailLabels } from "../../progress-report-i18n";

const TABLE_WIDTH = 1176;
const HEADER_HEIGHT = 45;
const ROW_HEIGHT = 60;

function MinistryCell({ row }: { row: ProgressReportMinistryRow }) {
  return (
    <Box
      sx={{
        width: "100%",
        minWidth: 0,
        display: "flex",
        alignItems: "center",
        gap: "8px",
      }}
    >
      {row.logo ? (
        <Box
          component="img"
          src={row.logo}
          alt={row.name}
          sx={{
            width: 28,
            height: 28,
            borderRadius: "50%",
            objectFit: "contain",
            flexShrink: 0,
          }}
        />
      ) : (
        <Box
          aria-hidden="true"
          sx={{
            width: 28,
            height: 28,
            borderRadius: "50%",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            flexShrink: 0,
            bgcolor: "action.hover",
            color: "text.secondary",
            fontSize: 12,
            fontWeight: 600,
          }}
        >
          {row.name.charAt(0).toUpperCase()}
        </Box>
      )}

      <Typography
        noWrap
        title={row.name}
        sx={{
          minWidth: 0,
          fontSize: 13,
          fontWeight: 500,
          lineHeight: "16px",
          color: "text.primary",
        }}
      >
        {row.name}
      </Typography>
    </Box>
  );
}

function IssueCountCell({ count }: { count: number }) {
  const { language } = useAppLanguage();

  return (
    <Box
      sx={{
        width: 28,
        height: 28,
        borderRadius: "50%",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        bgcolor: "#f04438",
        color: "#ffffff",
        fontSize: 13,
        fontWeight: 500,
      }}
    >
      {formatNumber(count, language)}
    </Box>
  );
}

function AttachmentCell({
  attachment,
}: {
  attachment: UploadedFileMetadata | string | null;
}) {
  if (!attachment) {
    return <Typography sx={{ fontSize: 12 }}>-</Typography>;
  }

  const isMetadata = typeof attachment !== "string";
  const name = isMetadata ? attachment.name : attachment;
  const displayName = getDisplayFileName(name, "-");
  const link = isMetadata ? getDocumentUrl(attachment.path) : null;

  return (
    <Box
      component={link ? "a" : "div"}
      href={link ?? undefined}
      target={link ? "_blank" : undefined}
      rel={link ? "noopener noreferrer" : undefined}
      sx={{
        width: "100%",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        gap: "8px",
        color: "inherit",
        textDecoration: "none",
      }}
    >
      <PdfDocumentIcon size={20} />
      <Typography
        noWrap
        sx={{ fontSize: 12, fontWeight: 500, color: "text.primary" }}
      >
        {displayName}
      </Typography>
    </Box>
  );
}

function MinistryActionsMenu({
  labels,
  reportId,
  ministryId,
}: {
  labels: ProgressReportDetailLabels;
  reportId: string;
  ministryId: number;
}) {
  const router = useRouter();
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
  const menuOpen = Boolean(anchorEl);

  const openMenu = (event: MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const closeMenu = () => {
    setAnchorEl(null);
  };

  const viewDetail = () => {
    closeMenu();
    router.push(
      `/cdc-gpsf/progress-reports/${reportId}/ministries/${ministryId}`,
    );
  };

  const menuItemSx = {
    minHeight: 44,
    px: 2,
    gap: 1.5,
    color: isDark ? alpha("#ffffff", 0.86) : "#414651",
    fontSize: 13,
    fontWeight: 500,
  } as const;

  return (
    <>
      <IconButton
        size="small"
        aria-label={labels.openActions}
        aria-haspopup="menu"
        aria-expanded={menuOpen ? "true" : undefined}
        onClick={openMenu}
        sx={{ color: "text.secondary" }}
      >
        <MoreVertIcon sx={{ fontSize: 22 }} />
      </IconButton>

      <Menu
        anchorEl={anchorEl}
        open={menuOpen}
        onClose={closeMenu}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        transformOrigin={{ vertical: "top", horizontal: "right" }}
        slotProps={{
          paper: {
            sx: {
              mt: 0.5,
              minWidth: 220,
              borderRadius: "12px",
              border: `1px solid ${isDark ? alpha("#ffffff", 0.12) : "#f5f5f5"}`,
              bgcolor: isDark ? "#101828" : "#ffffff",
              boxShadow: isDark
                ? "0 12px 30px rgba(0, 0, 0, 0.5)"
                : "0px 0px 10.6px rgba(0, 0, 0, 0.1)",
            },
          },
        }}
      >
        <MenuItem onClick={viewDetail} sx={menuItemSx}>
          <EyeViewIcon
            sx={{
              fontSize: 20,
              color: isDark ? alpha("#ffffff", 0.72) : "#717680",
            }}
          />
          {labels.viewDetail}
        </MenuItem>

        <MenuItem onClick={closeMenu} sx={menuItemSx}>
          <ExportCommentIcon
            sx={{
              fontSize: 20,
              color: isDark ? alpha("#ffffff", 0.72) : "#717680",
            }}
          />
          {labels.exportComment}
        </MenuItem>
      </Menu>
    </>
  );
}

function getDetailTableColumns(
  labels: ProgressReportDetailLabels,
  reportId: string,
): DataTableColDef<ProgressReportMinistryRow>[] {
  return [
    {
      field: "no",
      headerName: labels.columns.no,
      width: 50,
      minWidth: 50,
      flex: 0,
      align: "center",
      headerAlign: "center",
      sortable: false,
      filterable: false,
      disableColumnMenu: true,
      renderCell: (params) => (
        <DataTableNumberCell value={params.row.id} />
      ),
    },
    {
      field: "name",
      headerName: labels.columns.name,
      width: 588,
      minWidth: 588,
      flex: 0,
      headerAlign: "center",
      sortable: false,
      filterable: false,
      disableColumnMenu: true,
      renderCell: (params) => <MinistryCell row={params.row} />,
    },
    {
      field: "issueCount",
      headerName: labels.columns.issueCount,
      width: 150,
      minWidth: 150,
      flex: 0,
      align: "center",
      headerAlign: "center",
      sortable: false,
      filterable: false,
      disableColumnMenu: true,
      renderCell: (params) => <IssueCountCell count={params.row.issueCount} />,
    },
    {
      field: "attachment",
      headerName: labels.columns.attachment,
      width: 250,
      minWidth: 250,
      flex: 0,
      align: "center",
      headerAlign: "center",
      sortable: false,
      filterable: false,
      disableColumnMenu: true,
      renderCell: (params) => (
        <AttachmentCell attachment={params.row.attachment} />
      ),
    },
    {
      field: "action",
      headerName: labels.columns.action,
      width: 138,
      minWidth: 138,
      flex: 0,
      align: "center",
      headerAlign: "center",
      sortable: false,
      filterable: false,
      disableColumnMenu: true,
      renderCell: (params) => (
        <MinistryActionsMenu
          labels={labels}
          reportId={reportId}
          ministryId={params.row.ministryId ?? params.row.id}
        />
      ),
    },
  ];
}

type ProgressReportDetailTableProps = {
  rows: ProgressReportMinistryRow[];
  labels: ProgressReportDetailLabels;
  reportId: string;
  loading?: boolean;
  error?: string | null;
};

export function ProgressReportDetailTable({
  rows,
  labels,
  reportId,
  loading = false,
  error = null,
}: ProgressReportDetailTableProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const columns = useMemo(
    () => getDetailTableColumns(labels, reportId),
    [labels, reportId],
  );

  const visibleRowCount = rows.length === 0 ? 3 : rows.length;
  const tableHeight = HEADER_HEIGHT + visibleRowCount * ROW_HEIGHT;

  const dataGridSx = useMemo<SxProps<Theme>>(() => {
    const headerBackground = isDark ? alpha("#ffffff", 0.06) : "#ddedfb";
    const bodyBackground = isDark ? "#101828" : "#ffffff";
    const borderColor = isDark ? alpha("#ffffff", 0.08) : "#f5f5f5";

    return {
      border: "none",
      minWidth: TABLE_WIDTH,

      "& .MuiDataGrid-columnHeaders": {
        bgcolor: headerBackground,
        borderBottom: `1px solid ${borderColor}`,
      },
      "& .MuiDataGrid-columnHeader": {
        px: 2,
        bgcolor: headerBackground,
      },
      "& .MuiDataGrid-columnHeaderTitle": {
        fontSize: 12,
        fontWeight: 400,
        color: isDark ? alpha("#ffffff", 0.72) : "#717680",
      },
      "& .MuiDataGrid-cell": {
        px: 2,
        py: 0,
        bgcolor: bodyBackground,
        borderColor,
        color: isDark ? alpha("#ffffff", 0.86) : "#181d27",
      },
      "& .MuiDataGrid-row": {
        bgcolor: bodyBackground,
      },
      "& .MuiDataGrid-row:hover": {
        bgcolor: isDark ? alpha("#ffffff", 0.04) : "#f9fafb",
      },
      "& .MuiDataGrid-withBorderColor": {
        borderColor,
      },
      "& .MuiDataGrid-virtualScroller": {
        overflowX: "auto !important",
        overflowY: "hidden !important",
      },
    };
  }, [isDark]);

  return (
    <DataTable
      rows={rows}
      columns={columns}
      getRowId={(row) => row.id}
      emptyMessage={labels.emptyMessage}
      loading={loading}
      error={error}
      height={tableHeight}
      hidePagination
      rowHeight={ROW_HEIGHT}
      columnHeaderHeight={HEADER_HEIGHT}
      dataGridSx={dataGridSx}
      paperSx={{
        width: "100%",
        minWidth: 0,
        overflowX: "auto",
        overflowY: "hidden",
        borderRadius: "12px 12px 0 0",
        border: `1px solid ${isDark ? alpha("#ffffff", 0.1) : "#e9eaeb"}`,
      }}
    />
  );
}
