"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;
};

// export type FGRecord = {
//   id: string | number;
//   code: string;
//   name: string;
//   inStockQty: number;
//   productionQty?: number;
//   purchaseQty?: number;
// };

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

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

  //   const apiRef = useGridApiRef();

  // const [pagingController, setPagingController] = useState([
  //   {
  //     pageNum: 1,
  //     pageSize: 10,
  //     totalCount: 0,
  //   },
  //   {
  //     pageNum: 1,
  //     pageSize: 10,
  //     totalCount: 0,
  //   },
  //   {
  //     pageNum: 1,
  //     pageSize: 10,
  //     totalCount: 0,
  //   },
  //   {
  //     pageNum: 1,
  //     pageSize: 10,
  //     totalCount: 0,
  //   },
  //   {
  //     pageNum: 1,
  //     pageSize: 10,
  //     totalCount: 0,
  //   },
  //   {
  //     pageNum: 1,
  //     pageSize: 10,
  //     totalCount: 0,
  //   },
  //   {
  //     pageNum: 1,
  //     pageSize: 10,
  //     totalCount: 0,
  //   },
  //   {
  //     pageNum: 1,
  //     pageSize: 10,
  //     totalCount: 0,
  //   },
  // ]);

  // const updatePagingController = (updatedObj) => {
  //   setPagingController((prevState) => {
  //     return prevState.map((item, index) => {
  //       if (index === updatedObj?.index) {
  //         return {
  //           ...item,
  //           pageNum: item.pageNum,
  //           pageSize: item.pageSize,
  //           totalCount: item.totalCount,
  //         };
  //       } else return item;
  //     });
  //   });
  // };

  const columns = useMemo<Column<DetailedProdScheduleLineResult>[]>(
    () => [
      {
        field: "jobNo",
        label: t("Job No."),
        type: "read-only",
        // editable: true,
      },
      {
        field: "code",
        label: t("code"),
        type: "read-only",
        // editable: true,
      },
      {
        field: "name",
        label: t("name"),
        type: "read-only",
      },
      {
        field: "type",
        label: t("type"),
        type: "read-only",
        renderCell: (row) => {
          return t(row.type);
        },
        // editable: true,
      },
      // {
      //     field: "inStockQty",
      //     label: "Available Qty",
      //     type: 'read-only',
      //     style: {
      //         textAlign: "right",
      //     },
      //     // editable: true,
      //     renderCell: (row: FGRecord) => {
      //         if (typeof (row.inStockQty) == "number") {
      //             return decimalFormatter.format(row.inStockQty)
      //         }
      //         return row.inStockQty
      //     }
      // },
      {
        field: "demandQty",
        label: t("Demand Qty"),
        type: "input-number",
        style: {
          textAlign: "right",
          // width: "100px",
        },
        renderCell: (row) => {
          if (typeof row.demandQty == "number") {
            return integerFormatter.format(row.demandQty ?? 0);
          }
          return row.demandQty;
        },
      },
      {
        field: "uomName",
        label: t("UoM"),
        type: "read-only",
        style: {
          textAlign: "left",
          // width: "100px",
        },
        renderCell: (row) => {
          return row.uomName;
        },
      },
      {
        field: "prodTimeInMinute",
        label: t("Estimated Production Time"),
        type: "read-only",
        style: {
          textAlign: "right",
          // width: "100px",
        },
        renderCell: (row) => {
          return <ProdTimeColumn prodTimeInMinute={row.prodTimeInMinute} />
        }
      },
      {
        field: "priority",
        label: t("Production Priority"),
        type: "read-only",
        style: {
          textAlign: "right",
          // width: "100px",
        },
        // editable: true,
      },
    ],
    [],
  );

  return (
    <Grid container spacing={2}>
      {/* <Grid item xs={12} key={"all"}>
                <Typography variant="overline" display="block" marginBlockEnd={1}>
                    {t("FG Demand List (7 Days)")}
                </Typography>
                <EditableSearchResults<FGRecord>
                    index={7}
                    items={fakeOverallRecords}
                    columns={overallColumns}
                    setPagingController={updatePagingController}
                    pagingController={pagingController[7]}
                    isAutoPaging={false}
                    isEditable={false}
                    isEdit={isEdit}
                    hasCollapse={true}
                />
            </Grid> */}
      {/* {dayPeriod.map((date, index) => ( */}
      <Grid item xs={12}>
        {/* <Typography variant="overline" display="block" marginBlockEnd={1}>
                        {`${t("FG Demand Date")}: ${date}`}
                    </Typography> */}
        <ScheduleTable<DetailedProdScheduleLineResult>
          type={type}
          // items={fakeRecords[index]} // Use the corresponding records for the day
          items={getValues("prodScheduleLines")} // Use the corresponding records for the day
          columns={columns}
          // setPagingController={updatePagingController}
          // pagingController={pagingController[index]}
          isAutoPaging={false}
          isEditable={true}
          isEdit={isEdit}
          hasCollapse={true}
          onReleaseClick={onReleaseClick}
          onEditClick={onEditClick}
          handleEditChange={handleEditChange}
          onSaveClick={onSaveClick}
          onCancelClick={onCancelClick}
        />
      </Grid>
      {/* ))} */}
    </Grid>
  );
};
export default ViewByFGDetails;
