"use client";

import { apiDefaultParams } from "@/constants/Api_Params";
import { AdminStatus } from "@/constants/enums";
import {
  useAdminListInfiniteQuery,
  useChangeAdminStatus,
  useDeleteAdmin,
} from "@/hooks/queries";
import { IUser, TChangeAdminStatusCredentials } from "@/lib/api";
import { usePathname, useRouter } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";

export const useAdminsPresenter = () => {
  const [isChangeStatusModalOpen, setIsChangeStatusModalOpen] = useState(false);
  const [currentUser, setCurrentUser] = useState<IUser | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [status, setStatus] = useState<string>(
    currentUser?.status ?? AdminStatus.ACTIVE,
  );
  const router = useRouter();
  const {
    register,
    formState: { errors },
    handleSubmit,
  } = useForm<TChangeAdminStatusCredentials>({
    mode: "onChange",
    defaultValues: {
      status: currentUser?.status,
    },
  });
  const [params, setParams] = useState<Record<string, any>>({
    ...apiDefaultParams,
  });
  const pathName = usePathname();
  const { data, isPending } = useAdminListInfiniteQuery(params);
  const { mutate: deleteAdmin } = useDeleteAdmin(() => {
    setIsModalOpen(false);
  });

  const onConfirmDelete = () => {
    if (currentUser) {
      deleteAdmin(currentUser.id);
    }
  };
  const { mutate: changeStatus } = useChangeAdminStatus({
    id: currentUser?.id ?? "",
    successCallback: () => {
      setIsChangeStatusModalOpen(false);
    },
  });
  const allUsers = data?.pages.flatMap((page) => page.data.users) ?? [];
  const columns = [
    "row",
    "full name",
    "email",
    "role",
    "username",
    "status",
    "actions",
  ];
  return {
    allUsers,
    columns,
    isPending,
    onConfirmDelete,
    isModalOpen,
    setIsModalOpen,
    router,
    setCurrentUser,
    pathName,
    status,
    setStatus,
    changeStatus,
    isChangeStatusModalOpen,
    currentUser,
    setIsChangeStatusModalOpen,
    register,
    errors,
    handleSubmit,
  };
};
