"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { EquipmentTypeResult } from "@/app/api/settings/equipmentType";
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";
import { EquipmentTypeResultResponse } from "@/app/api/settings/equipmentType";
type Props = {
  equipmentTypes: EquipmentTypeResult[];
};
type SearchQuery = Partial<Omit<EquipmentTypeResult, "id">>;
type SearchParamNames = keyof SearchQuery;

const EquipmentTypeSearch: React.FC<Props> = ({ equipmentTypes }) => {
  const [filteredEquipmentTypes, setFilteredEquipmentTypes] =
    useState<EquipmentTypeResult[]>(equipmentTypes);
  const { t } = useTranslation("common");
  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(() => {
    const searchCriteria: Criterion<SearchParamNames>[] = [
      { label: t("Code"), paramName: "code", type: "text" },
      { label: t("Description"), paramName: "description", type: "text" },
    ];
    return searchCriteria;
  }, [t, equipmentTypes]);

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

  const onDeleteClick = useCallback(
    (equipmentType: EquipmentTypeResult) => {},
    [router],
  );

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

  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<EquipmentTypeResultResponse>(
          `${NEXT_PUBLIC_API_URL}/EquipmentType/getRecordByPage`,
          { params },
        );
        console.log(response);
        if (response.status == 200) {
          setFilteredEquipmentTypes(response.data.records);
          setTotalCount(response.data.total);
          return response; // Return the data from the response
        } else {
          throw "400";
        }
      } catch (error) {
        console.error("Error fetching equipment types:", 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(() => {
    setFilteredEquipmentTypes(equipmentTypes);
  }, [equipmentTypes]);

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

export default EquipmentTypeSearch;
