"use client";

import { CreateItemInputs } from "@/app/api/settings/item/actions";
import {
  GridColDef,
  GridRowModel,
  GridRenderEditCellParams,
  GridEditInputCell,
  GridRowSelectionModel,
  useGridApiRef,
} from "@mui/x-data-grid";
import { MutableRefObject, useCallback, useMemo, useState } from "react";
import { useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { Box, Grid, Tooltip, Typography } from "@mui/material";
import { GridApiCommunity } from "@mui/x-data-grid/internals";
import { decimalFormatter, integerFormatter } from "@/app/utils/formatUtil";
import { DetailedProdScheduleLineResult, DetailedProdScheduleResult, ScheduleType } from "@/app/api/scheduling";
import ProdTimeColumn from "./ProdTimeColumn";
import ScheduleTable, { Column } from "../ScheduleTable/ScheduleTable";

type Props = {
  apiRef: MutableRefObject<GridApiCommunity>;
  isEdit: boolean;
  type: ScheduleType;
  onReleaseClick: (item: DetailedProdScheduleLineResult) => void;
  onEditClick: (rowId: number) => void;
  handleEditChange: (rowId: number, fieldName: keyof DetailedProdScheduleLineResult, newValue: number | string) => void;
  onSaveClick: (item: DetailedProdScheduleLineResult) => void;
  onCancelClick: (rowId: number) => void;
};

const ViewByFGDetails: React.FC<Props> = ({ 
  apiRef, 
  isEdit, 
  type, 
  onReleaseClick, 
  onEditClick, 
  handleEditChange, 
  onSaveClick, 
  onCancelClick 
}) => {
  const {
    t,
    i18n: { language },
  } = useTranslation("schedule");

  const {
    getValues,
    formState: { errors, defaultValues, touchedFields },
  } = useFormContext<DetailedProdScheduleResult>();

  const columns = useMemo<Column<DetailedProdScheduleLineResult>[]>(
    () => [
      {
        field: "jobNo",
        label: t("Job No."),
        type: "read-only",
      },
      {
        field: "code",
        label: t("code"),
        type: "read-only",
      },
      {
        field: "name",
        label: t("name"),
        type: "read-only",
      },
      {
        field: "type",
        label: t("type"),
        type: "read-only",
        renderCell: (row) => <>{t(row.type)}</>,
      },
      {
        field: "demandQty",
        label: t("Demand Qty"),
        type: "input-number",
        style: { textAlign: "right" } as any, // Use 'as any' to bypass strict CSS validation
        renderCell: (row) => <>{integerFormatter.format(row.demandQty ?? 0)}</>,
      },
      {
        field: "uomName",
        label: t("UoM"),
        type: "read-only",
        renderCell: (row) => <>{row.uomName}</>,
      },
      // --- Added Avg Usage, Stock, Days Left, and Job Order Count ---
      {
        field: "avgQtyLastMonth", // This MUST match the key in the object
        label: t("Avg Qty Last Month"),
        type: "read-only",
        // Ensure 'row' has the property 'avgQtyLastMonth'
        renderCell: (row) => <>{decimalFormatter.format(row.avgQtyLastMonth ?? 0)}</>,
      },
      {
        field: "stockQty",
        label: t("Stock Qty"),
        type: "read-only",
        style: { textAlign: "right" } as any,
        renderCell: (row) => <>{decimalFormatter.format(row.stockQty ?? 0)}</>,
      },
      {
        field: "daysLeft",
        label: t("Days Left"),
        type: "read-only",
        style: { textAlign: "right" } as any,
        renderCell: (row) => <>{row.daysLeft ?? 0}</>,
      },
      {
        field: "outputQty",
        label: t("Output Qty"),
        type: "read-only",
        style: { textAlign: "right", fontWeight: "bold" } as any,
        renderCell: (row) => <>{row.outputQty ?? 0}</>,
      },
      {
        field: "needNoOfJobOrder",
        label: t("Batch Need"),
        type: "read-only",
        style: { textAlign: "right", fontWeight: "bold" } as any,
        renderCell: (row) => <>{row.needNoOfJobOrder ?? 0}</>,
      },
      // -------------------------------------------------------------
      {
        field: "priority",
        label: t("Production Priority"),
        type: "read-only",
        style: { textAlign: "right" } as any,
      },
    ],
    [t]
  );

  return (
    <Grid container spacing={2}>
      <Grid item xs={12}>
        <ScheduleTable<DetailedProdScheduleLineResult>
          type={type}
          items={getValues("prodScheduleLines")}
          columns={columns}
          isAutoPaging={false}
          isEditable={true}
          isEdit={isEdit}
          hasCollapse={true}
          onReleaseClick={onReleaseClick}
          onEditClick={onEditClick}
          handleEditChange={handleEditChange}
          onSaveClick={onSaveClick}
          onCancelClick={onCancelClick}
        />
      </Grid>
    </Grid>
  );
}; // Added missing closing brace

export default ViewByFGDetails;