"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";
import { deleteDialog, successDialog } from "../Swal/CustomAlerts";
import { deleteQcCategory } from "@/app/api/settings/qcCategory/actions";
import Delete from "@mui/icons-material/Delete";
import { usePathname, useRouter } from "next/navigation";

interface Props {
  qcCategories: QcCategoryResult[];
}

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

const QcCategorySearch: React.FC<Props> = ({ qcCategories }) => {
  const { t } = useTranslation("qcCategory");
  const router = useRouter();
  const pathname = usePathname();

  // 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) => {
      router.push(`${pathname}/edit?id=${qcCategory.id}`);
  }, [router]);

  const handleDelete = useCallback((qcCategory: QcCategoryResult) => {
    deleteDialog(async () => {
      qcCategories = await deleteQcCategory(qcCategory.id);
      setFilteredQcCategories(qcCategories);

      await successDialog(t("Delete Success"), t);
    }, t);
  }, []);
  
  const columnWidthSx = (width = "10%") => {
    return { width: width, whiteSpace: "nowrap" };
  };

  const columns = useMemo<Column<QcCategoryResult>[]>(
    () => [
      {
        name: "id",
        label: t("Details"),
        onClick: onQcCategoryClick,
        buttonIcon: <EditNote />,
        sx: columnWidthSx("5%"),
      },
      { name: "code", label: t("Code"), sx: columnWidthSx("15%"), },
      { name: "name", label: t("Name"), sx: columnWidthSx("30%"), },
      // { name: "description", label: t("Description"), sx: columnWidthSx("50%"), },
      {
        name: "id",
        label: t("Delete"),
        onClick: handleDelete,
        buttonIcon: <Delete />,
        buttonColor: "error",
        sx: columnWidthSx("5%"),
      },
    ],
    [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;
