"use client";

import React, { useCallback, useEffect, useMemo, useState } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import SearchResults, { Column } from "../SearchResults";
import { EditNote } from "@mui/icons-material";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslation } from "react-i18next";
import { ScheduleType } from "@/app/api/scheduling";
import {
  ProdScheduleResult,
  SearchProdSchedule,
  fetchDetailedProdSchedules,
  fetchProdSchedules,
  testDetailedSchedule,
} from "@/app/api/scheduling/actions";
import { defaultPagingController } from "../SearchResults/SearchResults";
import { arrayToDateString, arrayToDayjs, decimalFormatter } from "@/app/utils/formatUtil";
import dayjs from "dayjs";
import { orderBy, uniqBy, upperFirst } from "lodash";
import { Button, Stack } from "@mui/material";
import isToday from 'dayjs/plugin/isToday';
import useUploadContext from "../UploadProvider/useUploadContext";
dayjs.extend(isToday);

// may need move to "index" or "actions"
// type RecordStructure = {
//     id: number,
//     scheduledPeriod: string,
//     scheduledAt: string,
//     productCount: number,
// };

type Props = {
  type: ScheduleType;
  // records: RecordStructure[];
  defaultInputs: SearchProdSchedule;
};

type SearchQuery = Partial<
  Omit<SearchProdSchedule, "id" | "pageSize" | "pageNum">
>;
type SearchParamNames = keyof SearchQuery;

const DSOverview: React.FC<Props> = ({ type, defaultInputs }) => {
  const [filteredSchedules, setFilteredSchedules] = useState<
    ProdScheduleResult[]
  >([]);
  const { t } = useTranslation("schedule");
  const { setIsUploading } = useUploadContext();

  const router = useRouter();
  // const [filterObj, setFilterObj] = useState({});
  // const [tempSelectedValue, setTempSelectedValue] = useState({});
  const [pagingController, setPagingController] = useState(
    defaultPagingController,
  );
  const [totalCount, setTotalCount] = useState(0);
  const [inputs, setInputs] = useState(defaultInputs);
  const typeOptions = [
    {
      value: "detailed",
      label: t("Detailed"),
    },
    {
      value: "manual",
      label: t("Manual"),
    },
  ];

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(() => {
    const searchCriteria: Criterion<SearchParamNames>[] = [
      // {
      //   label: t("Schedule Period"),
      //   label2: t("Schedule Period To"),
      //   paramName: "schedulePeriod",
      //   type: "dateRange",
      // },
      { label: t("Production Date"), paramName: "scheduleAt", type: "date" },
      {
        label: t("Product Count"),
        paramName: "totalEstProdCount",
        type: "text",
      },
      {
        label: t("Type"),
        paramName: "types",
        type: "autocomplete",
        options: typeOptions,
      },
    ];
    return searchCriteria;
  }, [t]);

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

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

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

  const columns = useMemo<Column<ProdScheduleResult>[]>(
    () => [
      {
        name: "id",
        label: t("Details"),
        onClick: (record) => onDetailClick(record),
        buttonIcon: <EditNote />,
      },
      // {
      //   name: "schedulePeriod",
      //   label: t("Demand Forecast Period"),
      //   renderCell: (params) => {
      //     return `${arrayToDateString(
      //       params.schedulePeriod,
      //     )} - ${arrayToDateString(params.schedulePeriodTo)}`;
      //   },
      // },
      {
        name: "produceAt",
        label: t("Production Date"),
        renderCell: (params) => {
          return arrayToDateString(params.produceAt);
        },
      },
      {
        name: "totalEstProdCount",
        label: t("Product Count(s)"),
        headerAlign: "right",
        align: "right",
        renderCell: (params) => {
          return decimalFormatter.format(params.totalEstProdCount);
        },
      },
      {
        name: "type",
        label: t("Type"),
        renderCell: (params) => {
          return upperFirst(t(params.type));
        },
      },
      // {
      //     name: "action",
      //     label: t(""),
      //     buttonIcon: <GridDeleteIcon />,
      //     onClick: onDeleteClick,
      // },
    ],
    [filteredSchedules],
  );

  const refetchData = useCallback(
    async (
      query: Record<SearchParamNames, string> | SearchProdSchedule,
      actionType: "reset" | "search" | "paging",
    ) => {
      // console.log(query)
      const defaultTypes = ["detailed", "manual"];
      const convertedTypes = (
        query.types == undefined || typeof query.types == "string"
          ? query.types?.toLowerCase() == "all"
            ? defaultTypes
            : [query.types]
          : query.types.some((ele) => ele.toLowerCase() === "all")
            ? defaultTypes
            : query.types
      ) as ScheduleType[];

      const params: SearchProdSchedule = {
        scheduleAt: dayjs(query?.scheduleAt).isValid()
          ? query?.scheduleAt
          : undefined,
        schedulePeriod: dayjs(query?.schedulePeriod).isValid()
          ? query?.schedulePeriod
          : undefined,
        schedulePeriodTo: dayjs(query?.schedulePeriodTo).isValid()
          ? query?.schedulePeriodTo
          : undefined,
        totalEstProdCount: query?.totalEstProdCount
          ? Number(query?.totalEstProdCount)
          : undefined,
        types: convertedTypes,
        pageNum: pagingController.pageNum - 1,
        pageSize: pagingController.pageSize,
      };
      const response = await fetchDetailedProdSchedules(params);

      // console.log(response)
      if (response) {
        setTotalCount(response.total);
        switch (actionType) {
          case "reset":
          case "search":
            setFilteredSchedules(() => response.records);
            break;
          case "paging":
            setFilteredSchedules((fs) =>
            orderBy(
              uniqBy([...fs, ...response.records], "id"),
              ["id"], ["desc"]));
            break;
        }
      }
    },
    [pagingController, setPagingController],
  );

  useEffect(() => {
    refetchData(inputs, "paging");
  }, [pagingController]);

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

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

  // const refetchData = async (filterObj: SearchQuery | null) => {

  //     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(defaultInputs, "reset");
  }, []);

  const testDetailedScheduleClick = useCallback(async () => {
    try {
      setIsUploading(true)
      const response = await testDetailedSchedule(inputs.scheduleAt)
      if (response) {
        refetchData(inputs, "paging");
      }
    } catch(e) {
      console.log(e)
    } finally {
      setIsUploading(false)
    }
  }, [inputs])

  return (
    <>
      <Stack
        direction="row"
        justifyContent="flex-end"
        flexWrap="wrap"
        rowGap={2}
      >
        <Button
          variant="contained"
          onClick={testDetailedScheduleClick}
          // disabled={filteredSchedules.some(ele => arrayToDayjs(ele.scheduleAt).isToday())}
        >
          {t("Test Detailed Schedule")}
        </Button>
      </Stack>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          setInputs(() => ({
            scheduleAt: query?.scheduleAt,
            schedulePeriod: query?.schedulePeriod,
            schedulePeriodTo: query?.schedulePeriodTo,
            totalEstProdCount: Number(query?.totalEstProdCount),
            types: query.types as unknown as ScheduleType[],
          }));
          refetchData(query, "search");
        }}
        onReset={onReset}
      />
      <SearchResults<ProdScheduleResult>
        items={filteredSchedules}
        columns={columns}
        setPagingController={setPagingController}
        pagingController={pagingController}
        totalCount={totalCount}
      // isAutoPaging={false}
      // hasCollapse={false}
      />
    </>
  );
};

export default DSOverview;
