"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";
import { useRouter, useSearchParams } from "next/navigation";
import DeleteIcon from '@mui/icons-material/Delete';
import { deleteDialog, successDialog } from "../Swal/CustomAlerts";
import { deleteTaskTemplate } from "@/app/api/tasks/actions";

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 searchParams = useSearchParams()
  const router = useRouter()

  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) => {
    const params = new URLSearchParams(searchParams.toString())
    params.set("id", taskTemplate.id.toString())
    router.replace(`/tasks/edit?${params.toString()}`);
  }, []);

  const onDeleteClick = useCallback((taskTemplate: TaskTemplate) => {

    deleteDialog(async () => {
      await deleteTaskTemplate(taskTemplate.id)

      successDialog(t("Delete Success"), t)

      setFilteredTemplates((prev) => prev.filter((obj) => obj.id !== taskTemplate.id))
    }, t)
  }, []);

  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") },
      {
        name: "id",
        label: t("Delete"),
        onClick: onDeleteClick,
        buttonIcon: <DeleteIcon />,
        color: "error"
      },
    ],
    [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;
