"use client";

import React, { useCallback, useEffect, useMemo, useState } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { ItemsResult } from "@/app/api/settings/item";
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, { Column }  from "@/components/SearchResults/EditableSearchResults"; // Make sure to import Qs
import { ItemsResultResponse } from "@/app/api/settings/item";
type Props = {
  items: ItemsResult[];
};
type SearchQuery = Partial<Omit<ItemsResult, "id">>;
type SearchParamNames = keyof SearchQuery;

const RSSOverview: React.FC<Props> = ({ items }) => {
  const [filteredItems, setFilteredItems] = useState<ItemsResult[]>(
    items ?? [],
  );
  const { t } = useTranslation();
  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
    let title = "";
    const mode = "Search";
    let redirPath = "";
    title = "Product";
    redirPath = "/settings/rss";
    return [mode, redirPath];
  }, []);

  const handleSelectionChange = (selectedValues: string[]) => {
    setTempSelectedValue({
      ...tempSelectedValue,
      excludeDate: selectedValues,
    });
  };

  const dayOptions = [
    { label: t("Mon"), value: 1 },
    { label: t("Tue"), value: 2 },
    { label: t("Wed"), value: 3 },
    { label: t("Thu"), value: 4 },
    { label: t("Fri"), value: 5 },
    { label: t("Sat"), value: 6 },
    { label: t("Sun"), value: 7 },
  ];

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(() => {
    const searchCriteria: Criterion<SearchParamNames>[] = [
      { label: t("Finished Goods Name"), paramName: "name", type: "text" },
      {
        label: t("Exclude Date"),
        paramName: "shelfLife",
        type: "select",
        options: ["qcChecks"],
        // selectedValues: filterObj,
        handleSelectionChange: handleSelectionChange,
      },
    ];
    return searchCriteria;
  }, [t, items]);

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

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

  const columns = useMemo<Column<ItemsResult>[]>(
    () => [
      // {
      //     name: "id",
      //     label: t("Details"),
      //     onClick: ()=>{},
      //     buttonIcon: <EditNote />,
      // },
      // {
      //   name: "name",
      //   label: "Finished Goods Name",
      //   // type: "input",
      // },
      // {
      //   name: "excludeDate",
      //   label: t("Exclude Date"),
        // type: "multi-select",
        // options: dayOptions,
        // renderCell: (item: ItemsResult) => {
        //   console.log("[debug] render item", item);
        //   const selectedValues = (item.excludeDate as number[]) ?? []; // Assuming excludeDate is an array of numbers
        //   const selectedLabels = dayOptions
        //     .filter((option) => selectedValues.includes(option.value))
        //     .map((option) => option.label)
        //     .join(", "); // Join labels into a string

        //   return (
        //     <span onDoubleClick={() => handleEditClick(item.id as number)}>
        //       {selectedLabels || "None"}{" "}
        //       {/* Display "None" if no days are selected */}
        //     </span>
        //   );
        // },
      // {
      //     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<ItemsResultResponse>(
        `${NEXT_PUBLIC_API_URL}/items/getRecordByPage`,
        {
          params,
          paramsSerializer: (params) => {
            return Qs.stringify(params, { arrayFormat: "repeat" });
          },
        },
      );
      setFilteredItems(response.data.records);
      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(filterObj);
  }, [items, filterObj]);

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          setFilterObj({
            ...query,
          });
        }}
        onReset={onReset}
      />
      <EditableSearchResults<ItemsResult>
        index={1} // bug
        isEdit
        isEditable
        items={filteredItems}
        columns={columns}
        setPagingController={setPagingController}
        pagingController={pagingController}
        isAutoPaging={false}
        hasCollapse={false}
      />
    </>
  );
};

export default RSSOverview;
