"use client";

import SearchBox, { Criterion } from "../SearchBox";
import { useCallback, useEffect, useMemo, useState } from "react";
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 { UserGroupResult } from "@/app/api/group";
import { deleteGroup } from "@/app/api/group/actions";

interface Props {
  groups: UserGroupResult[];
}
type SearchQuery = Partial<Omit<UserGroupResult, "id">>;
type SearchParamNames = keyof SearchQuery;

const UserGroupSearch: React.FC<Props> = ({ groups }) => {
  const { t } = useTranslation();
  const [filteredGroups, setFilteredGroups] = useState(groups);
  const router = useRouter();

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

  const onUserClick = useCallback(
    (group: UserGroupResult) => {
      router.push(`/settings/group/edit?id=${group.id}`)
    },
    [router, t]
  );

  const onDeleteClick = useCallback((group: UserGroupResult) => {
    deleteDialog(async () => {
      await deleteGroup(group.id);
      successDialog(t("Delete Success"), t);

    }, t);
  }, []);

  useEffect(() => {
    setFilteredGroups(groups)
  }, [groups]);

  const columns = useMemo<Column<UserGroupResult>[]>(
    () => [
      {
        name: "action",
        label: t("Edit"),
        onClick: onUserClick,
        buttonIcon: <EditNote />,
      },
      { name: "name", label: t("Group Name") },
      { name: "description", label: t("Description") },
      {
        name: "action",
        label: t("Delete"),
        onClick: onDeleteClick,
        buttonIcon: <DeleteIcon />,
        color: "error"
      },
    ],
    [t]
  );

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
            setFilteredGroups(
              groups.filter(
                (u) =>
                u.name.toLowerCase().includes(query.name.toLowerCase()) &&
                u.description.toLowerCase().includes(query.description.toLowerCase()) 
              )
            )
        }}
      />
      <SearchResults<UserGroupResult> items={filteredGroups} columns={columns} />
    </>
  );
};
export default UserGroupSearch;
