"use client";

import SearchBox, { Criterion } from "../SearchBox";
import { useCallback, 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 { UserResult } from "@/app/api/user";
import { deleteUser } from "@/app/api/user/actions";

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

const UserSearch: React.FC<Props> = ({ users }) => {
  const { t } = useTranslation();
  const [filteredUser, setFilteredUser] = useState(users);
  const router = useRouter();

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

  const onUserClick = useCallback(
    (users: UserResult) => {
      console.log(users);
      router.push(`/settings/user/edit?id=${users.id}`)
    },
    [router, t]
  );

  const onDeleteClick = useCallback((users: UserResult) => {
    deleteDialog(async () => {
      await deleteUser(users.id);
      successDialog(t("Delete Success"), t);
    }, t);
  }, []);

  const columns = useMemo<Column<UserResult>[]>(
    () => [
      {
        name: "action",
        label: t("Edit"),
        onClick: onUserClick,
        buttonIcon: <EditNote />,
      },
      { name: "name", label: t("UserName") },
      { name: "fullName", label: t("FullName") },
      { name: "title", label: t("Title") },
      { name: "department", label: t("Department") },
      { name: "email", label: t("Email") },
      { name: "phone1", label: t("Phone") },
      {
        name: "action",
        label: t("Delete"),
        onClick: onDeleteClick,
        buttonIcon: <DeleteIcon />,
        color: "error"
      },
    ],
    [t]
  );

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
            // setFilteredUser(
            //   users.filter(
            //     (t) =>
            //     t.name.toLowerCase().includes(query.name.toLowerCase()) &&
            //     t.code.toLowerCase().includes(query.code.toLowerCase()) &&
            //     t.description.toLowerCase().includes(query.description.toLowerCase()) 
            //   )
            // )
        }}
      />
      <SearchResults<UserResult> items={filteredUser} columns={columns} />
    </>
  );
};
export default UserSearch;
