"use client";

import React, {useCallback, useEffect, useMemo, useState} from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { ItemsResult} from "@/app/api/settings/item";
import SearchResults, { Column } from "../SearchResults";
import { EditNote } from "@mui/icons-material";
import { useRouter, useSearchParams } from "next/navigation";
import { GridDeleteIcon } from "@mui/x-data-grid";
import { TypeEnum } from "@/app/utils/typeEnum";
import axios from "axios";
import {BASE_API_URL, NEXT_PUBLIC_API_URL} from "@/config/api";
import { useTranslation } from "react-i18next";
import axiosInstance from "@/app/(main)/axios/axiosInstance";
import Qs from 'qs';
import EditableSearchResults from "@/components/SearchResults/EditableSearchResults"; // Make sure to import Qs

type RecordStructure ={
    id: number,
    schedulePeriod: string,
    scheduleAt: string
};

type Props = {
    records: RecordStructure[];
};

type SearchQuery = Partial<Omit<ItemsResult, "id">>;
type SearchParamNames = keyof SearchQuery;

const RSOverview: React.FC<Props> = ({ records }) => {
    const [filteredItems, setFilteredItems] = useState<Object[]>(records ?? []);
    const { t } = useTranslation("items");
    const router = useRouter();
    const [filterObj, setFilterObj] = useState({});
    const [tempSelectedValue, setTempSelectedValue] = useState({});
    const [pagingController, setPagingController] = useState({
        pageNum: 1,
        pageSize: 10,
        totalCount: 0,
    })

    const [mode, redirPath] = useMemo(() => {
        // var typeId = TypeEnum.CONSUMABLE_ID
        var title = "";
        var mode = "Search";
        var redirPath = "";
        title = "Product";
        redirPath = "/scheduling/rough";
        return [mode, redirPath];
    }, []);

    const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
        () => {
            var searchCriteria: Criterion<SearchParamNames>[] = [
                { label: t("Schedule Period"), paramName: "schedulePeriod", type: "dateRange" },
                { label: t("Scheduled At"), paramName: "scheduleAt", type: "date" },
                { label: t("Product Count"), paramName: "productCount", type: "input" },
            ]
            return searchCriteria
        },
        [t, records]
    );

    // const onDetailClick = useCallback(
    //     (item: ItemsResult) => {
    //         router.push(`/settings/items/edit?id=${item.id}`);
    //     },
    //     [router]
    // );

    const onDeleteClick = useCallback(
        (item: ItemsResult) => {},
        [router]
    );

    const onDetailClick = (record: any) => {
        console.log("[debug] record", record);
        router.push(`/scheduling/rough/edit?id=${record.id}`);
    }

    const columns = useMemo<Column<ItemsResult>[]>(
        () => [
            {
                name: "id",
                label: t("Details"),
                onClick: (record)=>onDetailClick(record),
                buttonIcon: <EditNote />,
            },
            {
                name: "scheduledPeriod",
                label: "Demand Forecast Period",
            },
            {
                name: "scheduledAt",
                label: t("Scheduled At"),
            },
            {
                name: "productCount",
                label: t("Product Count(s)"),
            },
            // {
            //     name: "action",
            //     label: t(""),
            //     buttonIcon: <GridDeleteIcon />,
            //     onClick: onDeleteClick,
            // },
        ],
        [filteredItems]
    );

    useEffect(() => {
        refetchData(filterObj);

    }, [filterObj, pagingController.pageNum, pagingController.pageSize]);

    const refetchData = async (filterObj: SearchQuery) => {

        const authHeader = axiosInstance.defaults.headers['Authorization'];
        if (!authHeader) {
            return; // Exit the function if the token is not set
        }

        const params ={
            pageNum: pagingController.pageNum,
            pageSize: pagingController.pageSize,
            ...filterObj,
            ...tempSelectedValue,
        }

        try {
            const response = await axiosInstance.get<ItemsResult[]>(`${NEXT_PUBLIC_API_URL}/items/getRecordByPage`, {
                params,
                paramsSerializer: (params) => {
                    return Qs.stringify(params, { arrayFormat: 'repeat' });
                },
            });
            //setFilteredItems(response.data.records);
            setFilteredItems([
                {
                    id: 1,
                    scheduledPeriod: "2025-05-11 to 2025-05-17",
                    scheduledAt: "2025-05-07",
                    productCount: 13,
                },
                {
                    id: 2,
                    scheduledPeriod: "2025-05-18 to 2025-05-24",
                    scheduledAt: "2025-05-14",
                    productCount: 15,
                },
                {
                    id: 3,
                    scheduledPeriod: "2025-05-25 to 2025-05-31",
                    scheduledAt: "2025-05-21",
                    productCount: 13,
                },
            ])
            setPagingController({
                ...pagingController,
                totalCount: response.data.total
            })
            return response; // Return the data from the response
        } catch (error) {
            console.error('Error fetching items:', error);
            throw error; // Rethrow the error for further handling
        }
    };

    const onReset = useCallback(() => {
        //setFilteredItems(items ?? []);
        setFilterObj({});
        setTempSelectedValue({});
        refetchData();
    }, [records]);

    return (
        <>
            <SearchBox
                criteria={searchCriteria}
                onSearch={(query) => {
                    setFilterObj({
                        ...query
                    })
                }}
                onReset={onReset}
            />
            <SearchResults<ItemsResult>
                items={filteredItems}
                columns={columns}
                setPagingController={setPagingController}
                pagingController={pagingController}
                isAutoPaging={false}
            />
        </>
    );
};

export default RSOverview;
