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

interface Props {
  positions: PositionResult[];
  abilities: String[];
}

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

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

  const [filteredPositions, setFilteredPositions] = useState(positions);
  const maintainPosition = abilities.includes(MAINTAIN_POSITION)

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

  const onReset = useCallback(() => {
    setFilteredPositions(positions);
  }, [positions]);

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

  const onDeleteClick = useCallback((position: PositionResult) => {

    deleteDialog(async() => {
        await deletePosition(position.id)

        successDialog("Delete Success", t)

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

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

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          setFilteredPositions(
            positions.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<PositionResult>
        items={filteredPositions}
        columns={columns}
      />
    </>
  );
};

export default PositionSearch;
