"use client";

import { useCallback, useMemo, useState } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { ItemsResult } 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";

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 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 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())
              );
            })
          );
        }}
        onReset={onReset}
      />
      <SearchResults<ItemsResult> items={filteredItems} columns={columns} />
    </>
  );
};

export default ItemsSearch;
