"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 { useFieldArray, useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";
import InputDataGrid, { TableRow } from "../InputDataGrid/InputDataGrid";
import { Box, Grid, Tooltip, Typography } from "@mui/material";
import { ItemQc } from "@/app/api/settings/item";
import { QcChecksInputs } from "@/app/api/settings/qcCheck/actions";
import { GridApiCommunity } from "@mui/x-data-grid/internals";
import { RiceBowl } from "@mui/icons-material";
import ScheduleTable from "@/components/ScheduleTable";
import { Column } from "@/components/ScheduleTable/ScheduleTable";
import {
  arrayToDayjs,
  dayjsToDateString,
  decimalFormatter,
  integerFormatter,
} from "@/app/utils/formatUtil";
import {
  RoughProdScheduleLineResultByFg,
  RoughProdScheduleResult,
  ScheduleType,
} from "@/app/api/scheduling";

type Props = {
  apiRef: MutableRefObject<GridApiCommunity>;
  isEdit: boolean;
  type: ScheduleType;
  dayPeriod: string[];
};

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

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

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

  const { fields } = useFieldArray({
    control,
    name: "prodScheduleLinesByFg",
  });
  //   const apiRef = useGridApiRef();

  console.log("%c DayPeriod: ", "background: #222; color: #bada55", dayPeriod);

  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: {
    pageNum: number;
    pageSize: number;
    totalCount: number;
    index?: number | undefined;
  }) => {
    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<RoughProdScheduleLineResultByFg>[]>(
    () => [
      {
        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",
        // editable: true,
        renderCell: (row) => {
          return t(row.type)
        }
      },
      {
        field: "availableQty",
        label: t("Available Qty"),
        type: "read-only",
        style: {
          textAlign: "right",
        },
        // editable: true,
        renderCell: (row) => {
          if (typeof row.availableQty == "number") {
            return decimalFormatter.format(row.availableQty);
          }
          return row.availableQty;
        },
      },
      {
        field: "prodQty",
        label: t("Demand Qty"),
        type: "input",
        style: {
          textAlign: "right",
        },
        renderCell: (row) => {
          if (typeof row.prodQty == "number") {
            return decimalFormatter.format(row.prodQty ?? 0);
          }
          return row.prodQty;
        },
      },
      {
        field: "uomName",
        label: t("UoM"),
        type: "read-only",
        style: {
          textAlign: "left",
        },
        // editable: true,
        renderCell: (row) => {
          return row.uomName;
        },
      },
    ],
    [],
  );

  const overallColumns = useMemo<Column<RoughProdScheduleLineResultByFg>[]>(
    () => [
      {
        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: (params) => {
          return t(params.type);
        },
        // editable: true,
      },
      {
        field: "lastMonthAvgSales",
        label: t("Last Month Average Stock"),
        type: "read-only",
        style: {
          textAlign: "right",
        },
        renderCell: (row) => {
          if (typeof row.lastMonthAvgSales == "number") {
            return decimalFormatter.format(row.lastMonthAvgSales);
          }
          return row.lastMonthAvgSales;
        },
        // editable: true,
      },
      {
        field: "estCloseBal",
        label: t("Safety Stock"),
        type: "read-only",
        style: {
          textAlign: "right",
        },
        renderCell: (row) => {
          if (typeof row.estCloseBal == "number") {
            return decimalFormatter.format(row.estCloseBal);
          }
          return row.estCloseBal;
        },
        // editable: true,
      },
      {
        field: "availableQty",
        label: t("Available Qty"),
        type: "read-only",
        style: {
          textAlign: "right",
        },
        renderCell: (row) => {
          if (typeof row.availableQty == "number") {
            return decimalFormatter.format(row.availableQty);
          }
          return row.availableQty;
        },
        // editable: true,
      },
      {
        field: "prodQty",
        label: t("Demand Qty (7 Days)"),
        type: "read-only",
        style: {
          textAlign: "right",
        },
        renderCell: (row) => {
          if (typeof row.prodQty == "number") {
            return decimalFormatter.format(row.prodQty);
          }
          return row.prodQty;
        },
      },
      {
        field: "uomName",
        label: t("UoM"),
        type: "read-only",
        style: {
          textAlign: "left",
        },
        renderCell: (row) => {
          return row.uomName;
        },
      },
    ],
    [],
  );

  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>
        <ScheduleTable<RoughProdScheduleLineResultByFg>
          // index={7}
          type={type}
          items={getValues("prodScheduleLinesByFg")}
          columns={overallColumns}
          setPagingController={updatePagingController}
          pagingController={pagingController[7]}
          isAutoPaging={false}
          isEditable={false}
          isEdit={isEdit}
          hasCollapse={true}
        />
      </Grid>
      {dayPeriod.map((date, index) => (
        <Grid item xs={12} key={index}>
          <Typography variant="overline" display="block" marginBlockEnd={1}>
            {`${t("FG Demand Date")}: ${date}`}
          </Typography>
          <ScheduleTable<RoughProdScheduleLineResultByFg>
            type={type}
            items={
              getValues("prodScheduleLinesByFgByDate") &&
              Object.entries(getValues("prodScheduleLinesByFgByDate")).length >
                0
                ? getValues("prodScheduleLinesByFgByDate")[index + 1]
                : []
            } // Use the corresponding records for the day
            columns={columns}
            setPagingController={updatePagingController}
            pagingController={pagingController[index]}
            isAutoPaging={false}
            isEditable={true}
            isEdit={isEdit}
            hasCollapse={true}
          />
        </Grid>
      ))}
    </Grid>
  );
};
export default ViewByFGDetails;
