"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { ItemsResult, ItemsResultResponse } from "@/app/api/settings/item";
import { useTranslation } from "react-i18next";
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 axiosInstance from "@/app/(main)/axios/axiosInstance";

type Props = {
  items: ItemsResult[];
};
type SearchQuery = Partial<Omit<ItemsResult, "id">>;
type SearchParamNames = keyof SearchQuery;

const ItemsSearch: React.FC<Props> = ({ items }) => {
  const [filteredItems, setFilteredItems] = useState<ItemsResult[]>(items);
  const { t } = useTranslation("items");
  const router = useRouter();
  const [filterObj, setFilterObj] = useState({});
  const [pagingController, setPagingController] = useState({
    pageNum: 1,
    pageSize: 10,
    // totalCount: 0,
  });
  const [totalCount, setTotalCount] = useState(0)
  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(() => {
    var searchCriteria: Criterion<SearchParamNames>[] = [
      { label: t("Code"), paramName: "code", type: "text" },
      { label: t("Name"), paramName: "name", type: "text" },
    ];
    return searchCriteria;
  }, [t, items]);

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

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

  const columns = useMemo<Column<ItemsResult>[]>(
    () => [
      {
        name: "id",
        label: t("Details"),
        onClick: onDetailClick,
        buttonIcon: <EditNote />,
      },
      {
        name: "code",
        label: t("Code"),
      },
      {
        name: "name",
        label: t("Name"),
      },
      {
        name: "action",
        label: t(""),
        buttonIcon: <GridDeleteIcon />,
        onClick: onDeleteClick,
      },
    ],
    [filteredItems]
  );

  const refetchData = useCallback(
    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,
      };
      try {
        const response = await axiosInstance.get<ItemsResultResponse>(
          `${NEXT_PUBLIC_API_URL}/items/getRecordByPage`,
          { params }
        );
        console.log(response);
        if (response.status == 200) {
          setFilteredItems(response.data.records);
          setTotalCount(response.data.total)
          return response; // Return the data from the response
        } else {
          throw "400";
        }
      } catch (error) {
        console.error("Error fetching items:", error);
        throw error; // Rethrow the error for further handling
      }
    },
    [axiosInstance, pagingController.pageNum, pagingController.pageSize]
  );

  useEffect(() => {
    refetchData(filterObj);
  }, [filterObj, pagingController.pageNum, pagingController.pageSize]);

  const onReset = useCallback(() => {
    setFilteredItems(items);
  }, [items]);

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          // setFilteredItems(
          //   items.filter((pm) => {
          //     return (
          //       pm.code.toLowerCase().includes(query.code.toLowerCase()) &&
          //       pm.name.toLowerCase().includes(query.name.toLowerCase())
          //     );
          //   })
          // );
          setFilterObj({
            ...query,
          });
        }}
        onReset={onReset}
      />
      <SearchResults<ItemsResult>
        items={filteredItems}
        columns={columns}
        setPagingController={setPagingController}
        pagingController={pagingController}
        totalCount={totalCount}
        isAutoPaging={false}
      />
    </>
  );
};

export default ItemsSearch;
