"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import SearchBox, { Criterion } from "../SearchBox/index";
import { useTranslation } from "react-i18next";
import SearchResults, { Column } from "../SearchResults/index";
import EditNote from "@mui/icons-material/EditNote";
import DeleteIcon from "@mui/icons-material/Delete";
import { useRouter } from "next/navigation";
import { deleteDialog, successDialog } from "../Swal/CustomAlerts";
import { SkillResult } from "@/app/api/skill";
import { deleteSkill } from "@/app/api/skill/actions";

interface Props {
  skill: SkillResult[];
}

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

const SkillSearch: React.FC<Props> = ({ skill }) => {
  const { t } = useTranslation();
  const [filteredSkill, setFilteredSkill] = useState(skill);
  const router = useRouter();

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      {
        label: t("Skill Name"),
        paramName: "name",
        type: "text",
      },
      {
        label: t("Skill Code"),
        paramName: "code",
        type: "text",
      },
    ],
    [t]
  );

  const onSkillClick = useCallback(
    (skill: SkillResult) => {
      console.log(skill);
      const id = skill.id;
      router.push(`/settings/skill/edit?id=${id}`);
    },
    [router, t]
  );

  const deleteClick = useCallback((skill: SkillResult) => {
    deleteDialog(async () => {
      await deleteSkill(skill.id);
      successDialog("Delete Success", t);
      // setFilteredSkill((prev) => prev.filter((obj) => obj.id !== skill.id));
    }, t);
  }, []);

  const columns = useMemo<Column<SkillResult>[]>(
    () => [
      {
        name: "action",
        label: t("Actions"),
        onClick: onSkillClick,
        buttonIcon: <EditNote />,
      },
      { name: "name", label: t("name") },
      { name: "code", label: t("code") },
      { name: "description", label: t("description") },
      {
        name: "delete",
        label: t("Delete"),
        onClick: deleteClick,
        buttonIcon: <DeleteIcon />,
        color: "error", 
      },
    ],
    [t, onSkillClick, deleteClick]
  );

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          setFilteredSkill(
            skill.filter(
              (s) =>
                s.name.toLowerCase().includes(query.name.toLowerCase()) &&
                s.code.toLowerCase().includes(query.code.toLowerCase()) 
            )
          );
        }}
      />
      <SearchResults<SkillResult> items={filteredSkill} columns={columns} />
    </>
  );
};

export default SkillSearch;
