"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, useEffect, 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 EditableSearchResults, { Column } from "@/components/SearchResults/EditableSearchResults";
import { decimalFormatter } from "@/app/utils/formatUtil";
import { GridRenderCellParams } from "@mui/x-data-grid";
import { ProdScheduleLineResultByBom, ProdScheduleLineResultByBomByDate, ProdScheduleResult, ScheduleType } from "@/app/api/scheduling";
import ScheduleTable from "@/components/ScheduleTable";
import { Column } from "@/components/ScheduleTable/ScheduleTable";

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

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

// export type FGOverallRecord = {
//     id: string | number
//     code: string;
//     name: string;
//     type: string;
//     inStockQty: number;
//     purchaseQty: number;
//     purchaseQty1: number;
//     purchaseQty2: number;
//     purchaseQty3: number;
//     purchaseQty4: number;
//     purchaseQty5: number;
//     purchaseQty6: number;
//     purchaseQty7: number;
//     overallPurchaseQty: number;
// }

const ViewByBomDetails: React.FC<Props> = ({ apiRef, isEdit, type, dayPeriod }) => {
    const { t, i18n: { language }, } = useTranslation("schedule");
    const {
        control,
        getValues,
        formState: { errors, defaultValues, touchedFields },
    } = useFormContext<ProdScheduleResult>();
    //   const apiRef = useGridApiRef();

    const { fields } = useFieldArray({
        control,
        name: "prodScheduleLinesByBom"
    })

    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 overallColumns = useMemo<Column<any>[]>(
        () => [
            {
                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: "availableQty",
                label: t("Available Qty"),
                type: 'read-only',
                style: {
                    textAlign: "right",
                },
                renderCell: (row: ProdScheduleLineResultByBom) => {
                    if (typeof (row.availableQty) == "number") {
                        return decimalFormatter.format(row.availableQty)
                    }
                    return row.availableQty
                }
                // editable: true,
            },
            {
                field: "totalDemandQty",
                label: t("Total Demand Qty"),
                type: 'read-only',
                style: {
                    textAlign: "right",
                },
                renderCell: (row: ProdScheduleLineResultByBom) => {
                    if (typeof (row.totalDemandQty) == "number") {
                        return decimalFormatter.format(row.totalDemandQty)
                    }
                    return row.totalDemandQty
                }
            },
            {
                field: "demandQty1",
                label: t("Demand Qty (Day1)"),
                type: 'read-only',
                style: {
                    textAlign: "right",
                },
                renderCell: (row: ProdScheduleLineResultByBom) => {
                    if (typeof (row.demandQty1) == "number") {
                        return decimalFormatter.format(row.demandQty1)
                    }
                    return row.demandQty1
                }
            },
            {
                field: "demandQty2",
                label: t("Demand Qty (Day2)"),
                type: 'read-only',
                style: {
                    textAlign: "right",
                },
                renderCell: (row: ProdScheduleLineResultByBom) => {
                    if (typeof (row.demandQty2) == "number") {
                        return decimalFormatter.format(row.demandQty2)
                    }
                    return row.demandQty2
                }
            },
            {
                field: "demandQty3",
                label: t("Demand Qty (Day3)"),
                type: 'read-only',
                style: {
                    textAlign: "right",
                },
                renderCell: (row: ProdScheduleLineResultByBom) => {
                    if (typeof (row.demandQty3) == "number") {
                        return decimalFormatter.format(row.demandQty3)
                    }
                    return row.demandQty3
                }
            },
            {
                field: "demandQty4",
                label: t("Demand Qty (Day4)"),
                type: 'read-only',
                style: {
                    textAlign: "right",
                },
                renderCell: (row: ProdScheduleLineResultByBom) => {
                    if (typeof (row.demandQty4) == "number") {
                        return decimalFormatter.format(row.demandQty4)
                    }
                    return row.demandQty4
                }
            }, {
                field: "demandQty5",
                label: t("Demand Qty (Day5)"),
                type: 'read-only',
                style: {
                    textAlign: "right",
                },
                renderCell: (row: ProdScheduleLineResultByBom) => {
                    if (typeof (row.demandQty5) == "number") {
                        return decimalFormatter.format(row.demandQty5)
                    }
                    return row.demandQty5
                }
            },
            {
                field: "demandQty6",
                label: t("Demand Qty (Day6)"),
                type: 'read-only',
                style: {
                    textAlign: "right",
                },
                renderCell: (row: ProdScheduleLineResultByBom) => {
                    if (typeof (row.demandQty6) == "number") {
                        return decimalFormatter.format(row.demandQty6)
                    }
                    return row.demandQty6
                }
            },
            {
                field: "demandQty7",
                label: t("Demand Qty (Day7)"),
                type: 'read-only',
                style: {
                    textAlign: "right",
                },
                renderCell: (row: ProdScheduleLineResultByBom) => {
                    if (typeof (row.demandQty7) == "number") {
                        return decimalFormatter.format(row.demandQty7)
                    }
                    return row.demandQty7
                }
            },
        ],
        [t]
    );

    const columns = useMemo<Column<ProdScheduleLineResultByBomByDate>[]>(
        () => [
            {
                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)
                }
            },
            {
                field: "availableQty",
                label: t("Available Qty"),
                type: 'read-only',
                // editable: true,
                style: {
                    textAlign: "right",
                },
                renderCell: (row: ProdScheduleLineResultByBomByDate) => {
                    if (typeof (row.availableQty) == "number") {
                        return decimalFormatter.format(row.availableQty)
                    }
                    return row.availableQty
                }
            },
            {
                field: "demandQty",
                label: t("Demand Qty"),
                type: 'read-only',
                style: {
                    textAlign: "right",
                },
                renderCell: (row: ProdScheduleLineResultByBomByDate) => {
                    if (typeof (row.demandQty) == "number") {
                        return decimalFormatter.format(row.demandQty)
                    }
                    return row.demandQty
                }
            },
        ],
        []
    );

    console.log(getValues("prodScheduleLinesByBom"))

    return (
        <Grid container spacing={2}>
            <Grid item xs={12} key={"all"}>
                <Typography variant="overline" display="block" marginBlockEnd={1}>
                    {t("Material Demand List (7 Days)")}
                </Typography>
                <ScheduleTable<ProdScheduleLineResultByBom>
                    // index={7}
                    type={type}
                    items={getValues("prodScheduleLinesByBom")}
                    columns={overallColumns}
                    setPagingController={updatePagingController}
                    pagingController={pagingController[7]}
                    isAutoPaging={true}
                    isEditable={false}
                    isEdit={false}
                    hasCollapse={false}
                />
            </Grid>
            {dayPeriod.map((date, index) => (
                <Grid item xs={12} key={index}>
                    <Typography variant="overline" display="block" marginBlockEnd={1}>
                        {`${t("Material Demand Date")}: ${date}`}
                    </Typography>
                    <ScheduleTable<ProdScheduleLineResultByBomByDate>
                        // index={index}
                        type={type}
                        items={getValues("prodScheduleLinesByBomByDate")[index + 1]} // Use the corresponding records for the day
                        columns={columns}
                        setPagingController={updatePagingController}
                        pagingController={pagingController[index]}
                        isAutoPaging={true}
                        isEditable={false}
                        isEdit={isEdit}
                        hasCollapse={false}
                    />
                </Grid>
            ))}
        </Grid>
    );
};
export default ViewByBomDetails;
