"use client";

import React, { useCallback, useMemo, useState } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { useTranslation } from "react-i18next";
import SearchResults, { Column } from "../SearchResults";
import EditNote from "@mui/icons-material/EditNote";
import { QcCategoryResult } from "@/app/api/settings/qcCategory";

interface Props {
  qcCategories: QcCategoryResult[];
}

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

const QcCategorySearch: React.FC<Props> = ({ qcCategories }) => {
  const { t } = useTranslation("qcCategories");

  // If qcCategory searching is done on the server-side, then no need for this.
  const [filteredQcCategories, setFilteredQcCategories] =
    useState(qcCategories);

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      { label: t("Code"), paramName: "code", type: "text" },
      { label: t("Name"), paramName: "name", type: "text" },
    ],
    [t],
  );

  const onReset = useCallback(() => {
    setFilteredQcCategories(qcCategories);
  }, [qcCategories]);

  const onQcCategoryClick = useCallback((qcCategory: QcCategoryResult) => {
    console.log(qcCategory);
  }, []);

  const columns = useMemo<Column<QcCategoryResult>[]>(
    () => [
      {
        name: "id",
        label: t("Details"),
        onClick: onQcCategoryClick,
        buttonIcon: <EditNote />,
      },
      { name: "code", label: t("Code") },
      { name: "name", label: t("Name") },
    ],
    [t, onQcCategoryClick],
  );

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          setFilteredQcCategories(
            qcCategories.filter(
              (qc) =>
                qc.code.toLowerCase().includes(query.code.toLowerCase()) &&
                qc.name.toLowerCase().includes(query.name.toLowerCase()),
            ),
          );
        }}
        onReset={onReset}
      />
      <SearchResults<QcCategoryResult>
        items={filteredQcCategories}
        columns={columns}
      />
    </>
  );
};

export default QcCategorySearch;
