"use client";

import React, { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { BomScoreResult } from "@/app/api/bom";
import { GridColDef, GridValueFormatterParams } from "@mui/x-data-grid";
import StyledDataGrid from "../StyledDataGrid";
import Paper from "@mui/material/Paper";

interface Props {
  boms: BomScoreResult[];
}

const BomScoreTable: React.FC<Props> = ({ boms }) => {
  const { t } = useTranslation(["bomWeighting", "common"]);

  const columns = useMemo<GridColDef<BomScoreResult>[]>(
    () => [
      {
        field: "code",
        headerName: t("Item Code"),
        flex: 1,
        minWidth: 150,
      },
      {
        field: "name",
        headerName: t("Item Name"),
        flex: 1.5,
        minWidth: 220,
      },
      {
        field: "baseScore",
        headerName: t("Base Score"),
        flex: 1,
        minWidth: 140,
        sortable: false,
        valueFormatter: (params: GridValueFormatterParams) => {
          const v = params.value;
          if (v == null) return "";

          let num: number | null = null;
          if (typeof v === "number") {
            num = v;
          } else if (typeof v === "string") {
            num = parseFloat(v);
          } else if (typeof v === "object" && v !== null) {
            const obj = v as any;
            if (typeof obj.value === "number") {
              num = obj.value;
            } else if (typeof obj.toString === "function") {
              num = parseFloat(obj.toString());
            }
          }

          if (num == null || Number.isNaN(num)) return "";
          return num.toFixed(2);
        },
      },
    ],
    [t],
  );

  return (
    <Paper variant="outlined" sx={{ overflow: "hidden" }}>
      <StyledDataGrid
        rows={boms}
        columns={columns}
        getRowId={(row) => row.id}
        autoHeight
        disableRowSelectionOnClick
        hideFooterPagination={true}
        sx={{
          "& .MuiDataGrid-columnHeaderTitle": { fontSize: 15 },
          "& .MuiDataGrid-cell": { fontSize: 16 },
        }}
      />
    </Paper>
  );
};

export default BomScoreTable;

