"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 } from "next/navigation";
import { GridDeleteIcon } from "@mui/x-data-grid";
import axiosInstance from "@/app/(main)/axios/axiosInstance";
import { NEXT_PUBLIC_API_URL } from "@/config/api";

type Props = {
  equipments: EquipmentResult[];
};

type SearchQuery = Partial<Omit<EquipmentResult, "id">>;
type SearchParamNames = keyof SearchQuery;

const QrCodeHandleEquipmentSearch: React.FC<Props> = ({ equipments }) => {
  const [filteredEquipments, setFilteredEquipments] =
    useState<EquipmentResult[]>([]); 
  const { t } = useTranslation("common");
  const router = useRouter();
  const [filterObj, setFilterObj] = useState({});
  const [pagingController, setPagingController] = useState({
    pageNum: 1,
    pageSize: 10,
  });
  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, 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: "equipmentTypeId",
        label: t("Equipment Type"),
        sx: {minWidth: 180},
      },
      {
        name: "description",
        label: t("Description"),
      },
      {
        name: "action",
        label: t(""),
        buttonIcon: <GridDeleteIcon />,
        onClick: onDeleteClick,
      },
    ],
    [filteredEquipments],
  );

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

  const refetchData = useCallback(
    async (filterObj: SearchQuery, pageNum: number, pageSize: number) => {
      const authHeader = axiosInstance.defaults.headers["Authorization"];
      if (!authHeader) {
        setTimeout(() => {
          refetchData(filterObj, pageNum, pageSize);
        }, 10);
        return;
      }
      const params = {
        pageNum: pageNum,
        pageSize: 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;
      }
    },
    [],
  );

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

  const onReset = useCallback(() => {
    setFilterObj({});
    setPagingController({ pageNum: 1, pageSize: 10 });
  }, []);

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          setFilterObj({
            ...query,
          });
        }}
        onReset={onReset}
      />
      <SearchResults<EquipmentResult>
        items={filteredEquipments}
        columns={columns}
        setPagingController={setPagingController}
        pagingController={pagingController}
        totalCount={totalCount}
        isAutoPaging={false}
      />
    </>
  );
};

export default QrCodeHandleEquipmentSearch;