"use client";

import { useCallback, useMemo } from "react";

import Box from "@mui/material/Box";
import { alpha, useTheme } from "@mui/material/styles";
import type { SxProps, Theme } from "@mui/material/styles";

import { useAppLanguage } from "@/components/providers/app-language-provider";
import { DataTable } from "@/components/ui/data-table";
import {
  normalizeProgressReportLanguage,
  progressReportText,
  translateProgressReportValue,
} from "@/features/cdc-gpsf/progress-report/progress-report-i18n";

import type { ProgressReportRow } from "../../progress-report-data";
import { getProgressReportTableColumns } from "./progress-report-table-columns";
import { PROGRESS_REPORT_TABLE_CONFIG } from "./progress-report-table-config";

type Props = {
  rows: ProgressReportRow[];
  loading?: boolean;
  error?: string | null;
  onView?: (row: ProgressReportRow) => void;
};

export function ProgressReportTable({
  rows,
  loading = false,
  error = null,
  onView,
}: Props) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  // Header labels and cell values are shared with the CDC-GPSF table so both
  // pages read the same in English and Khmer.
  const { language } = useAppLanguage();
  const tableLanguage = normalizeProgressReportLanguage(language);
  const text = progressReportText[tableLanguage];

  const translateValue = useCallback(
    (value: string) => translateProgressReportValue(value, tableLanguage),
    [tableLanguage],
  );

  const columns = useMemo(
    () =>
      getProgressReportTableColumns(
        text.columns,
        translateValue,
        text.actionsMenu.viewDetail,
        { onView },
      ),
    [onView, text.actionsMenu.viewDetail, text.columns, translateValue],
  );

  const dataGridSx = useMemo<SxProps<Theme>>(() => {
    const headerBg = isDark ? alpha("#ffffff", 0.06) : "#ddedfb";
    const bodyBg = isDark ? "#101828" : "#ffffff";
    const rowHoverBg = isDark ? alpha("#ffffff", 0.04) : "#f9fafb";
    const borderColor = isDark ? "#263244" : "#f5f5f5";

    return {
      border: "none",
      width: "100%",

      "& .MuiDataGrid-columnHeadersInner": {
        minWidth: PROGRESS_REPORT_TABLE_CONFIG.minWidth,
      },

      "& .MuiDataGrid-virtualScrollerContent": {
        minWidth: PROGRESS_REPORT_TABLE_CONFIG.minWidth,
      },

      "& .MuiDataGrid-columnHeaders": {
        backgroundColor: headerBg,
        borderBottom: `1px solid ${borderColor}`,
      },

      "& .MuiDataGrid-columnHeader": {
        px: 2,
        backgroundColor: headerBg,
      },

      "& .MuiDataGrid-columnHeaderTitleContainer": {
        overflow: "visible",
      },

      "& .MuiDataGrid-columnHeaderTitle": {
        fontSize: 12,
        fontWeight: 400,
        whiteSpace: "nowrap",
        overflow: "visible",
        textOverflow: "clip",
        color: isDark ? alpha("#ffffff", 0.72) : "#717680",
      },

      "& .MuiDataGrid-cell": {
        px: 2,
        py: 0,
        color: isDark ? "#ffffff" : "#181d27",
        borderColor,
        borderBottom: `1px solid ${borderColor}`,
        bgcolor: bodyBg,
        display: "flex",
        alignItems: "center",
      },

      "& .MuiDataGrid-row": {
        bgcolor: bodyBg,
      },

      "& .MuiDataGrid-row:hover": {
        bgcolor: rowHoverBg,
      },

      "& .MuiDataGrid-cell[data-field='actions']": {
        justifyContent: "center",
      },

      "& .MuiDataGrid-withBorderColor": {
        borderColor,
      },

      "& .MuiDataGrid-main": {
        overflow: "hidden",
      },

      "& .MuiDataGrid-virtualScroller": {
        overflowX: "auto !important",
        overflowY: "auto !important",
      },

      "& .MuiDataGrid-cell:focus, & .MuiDataGrid-cell:focus-within": {
        outline: "none",
      },

      "& .MuiDataGrid-columnHeader:focus, & .MuiDataGrid-columnHeader:focus-within":
        {
          outline: "none",
        },
    };
  }, [isDark]);

  return (
    <Box
      sx={{
        flex: 1,
        minHeight: 0,
        display: "flex",
        flexDirection: "column",
      }}
    >
      <DataTable
        fillAvailableHeight
        rows={rows}
        columns={columns}
        getRowId={(row) => row.id}
        loading={loading}
        error={error}
        emptyMessage="No progress reports match the selected filters."
        pageSize={PROGRESS_REPORT_TABLE_CONFIG.pageSize}
        rowHeight={PROGRESS_REPORT_TABLE_CONFIG.rowHeight}
        columnHeaderHeight={PROGRESS_REPORT_TABLE_CONFIG.headerHeight}
        dataGridSx={dataGridSx}
        paperSx={{
          width: "100%",
          minWidth: 0,
          flex: 1,
          overflow: "hidden",
          borderRadius: "12px",
          border: isDark
            ? `1px solid ${alpha("#ffffff", 0.1)}`
            : "1px solid #e9eaeb",
        }}
      />
    </Box>
  );
}
