"use client";

import { TaskTemplate } from "@/app/api/tasks";
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";

interface Props {
  taskTemplates: TaskTemplate[];
}

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

const TaskTemplateSearch: React.FC<Props> = ({ taskTemplates }) => {
  const { t } = useTranslation("tasks");

  const [filteredTemplates, setFilteredTemplates] = useState(taskTemplates);
  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      { label: t("Task Template Code"), paramName: "code", type: "text" },
      { label: t("Task Template Name"), paramName: "name", type: "text" },
    ],
    [t],
  );
  const onReset = useCallback(() => {
    setFilteredTemplates(taskTemplates);
  }, [taskTemplates]);

  const onTaskClick = useCallback((taskTemplate: TaskTemplate) => {
    console.log(taskTemplate);
  }, []);

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

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          setFilteredTemplates(
            taskTemplates.filter(
              (task) =>
                task.code.toLowerCase().includes(query.code.toLowerCase()) &&
                task.name.toLowerCase().includes(query.name.toLowerCase()),
            ),
          );
        }}
        onReset={onReset}
      />
      <SearchResults items={filteredTemplates} columns={columns} />
    </>
  );
};

export default TaskTemplateSearch;
