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

interface Props {
  departments: DepartmentResult[];
  abilities: String[];
}

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

const DepartmentSearch: React.FC<Props> = ({ departments, abilities }) => {
  const { t } = useTranslation("departments");
  const router = useRouter();

  const [filteredDepartments, setFilteredDepartments] = useState(departments);
  const maintainDepartment = abilities.includes(MAINTAIN_DEPARTMENT)

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

  const onReset = useCallback(() => {
    setFilteredDepartments(departments);
  }, [departments]);

  const onProjectClick = useCallback((department: DepartmentResult) => {
    console.log(department.id)
    router.push(`/settings/department/edit?id=${department.id}`);
  }, [router]);

  const onDeleteClick = useCallback((department: DepartmentResult) => {

  deleteDialog(async() => {
        await deleteDepartment(department.id)

        successDialog("Delete Success", t)

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

  const columns = useMemo<Column<DepartmentResult>[]>(
    () => [
      {
        name: "id",
        label: t("Details"),
        onClick: onProjectClick,
        buttonIcon: <EditNote />,
        isHidden: !maintainDepartment,
      },
      { name: "code", label: t("Department Code") },
      { name: "name", label: t("Department Name") },
      { name: "description", label: t("Department Description") },
      {
        name: "id",
        label: t("Delete"),
        onClick: onDeleteClick,
        buttonIcon: <DeleteIcon />,
        color: "error",
        isHidden: !maintainDepartment,
      },
    ],
    [t, onProjectClick],
  );

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          setFilteredDepartments(
            departments.filter(
              (d) =>
                d.code.toLowerCase().includes(query.code.toLowerCase()) &&
                d.name.toLowerCase().includes(query.name.toLowerCase()) &&
                d.description.toLowerCase().includes(query.description.toLowerCase()) &&
                {/*(query.client === "All" || p.client === query.client) &&
                (query.category === "All" || p.category === query.category) &&
                (query.team === "All" || p.team === query.team), **/}
            ),
          );
        }}
        onReset={onReset}
      />
      <SearchResults<DepartmentResult>
        items={filteredDepartments}
        columns={columns}
      />
    </>
  );
};

export default DepartmentSearch;
