"use client";

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

const EquipmentSearch: React.FC<Props> = ({ equipments }) => {
  const [filteredEquipments, setFilteredEquipments] = useState<EquipmentResult[]>(equipments);
  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(() => {
    var searchCriteria: Criterion<SearchParamNames>[] = [
      { label: t("Code"), paramName: "code", type: "text" },
      { label: t("Description"), paramName: "description", type: "text" },
    ];
    return searchCriteria;
  }, [t, equipments]);

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

  const onDeleteClick = useCallback((equipment: EquipmentResult) => {}, [router]);

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


  interface ApiResponse<T> {
    records: T[];
    total: number;
  }

  const refetchData = useCallback(
    async (filterObj: SearchQuery) => {
      const authHeader = axiosInstance.defaults.headers["Authorization"];
      if (!authHeader) {
        return;
      }
      const params = {
        pageNum: pagingController.pageNum,
        pageSize: pagingController.pageSize,
        ...filterObj,
      };
      try {
        const response = await axiosInstance.get<ApiResponse<EquipmentResult>>(
          `${NEXT_PUBLIC_API_URL}/Equipment/getRecordByPage`,
          { params }
        );
        console.log(response);
        if (response.status == 200) {
          setFilteredEquipments(response.data.records);
          setTotalCount(response.data.total);
          return response;
        } else {
          throw "400";
        }
      } catch (error) {
        console.error("Error fetching equipment types:", error);
        throw error;
      }
    },
    [axiosInstance, pagingController.pageNum, pagingController.pageSize]
  );

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

  const onReset = useCallback(() => {
    setFilteredEquipments(equipments);
  }, [equipments]);

  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<EquipmentResult>
        items={filteredEquipments}
        columns={columns}
        setPagingController={setPagingController}
        pagingController={pagingController}
        totalCount={totalCount}
        isAutoPaging={false}
      />
    </>
  );
};

export default EquipmentSearch;
