"use client";

import {
  useAssignCompany,
  useCustomersInfiniteQuery,
  useDeleteCustomerQuery,
} from "@/hooks/queries";
import { TAssignCustomerToCompanyCredentials, TCustomer } from "@/lib/api";
import { usePathname, useRouter } from "next/navigation";
import { useState } from "react";

const useCustomerListPresenter = () => {
  const [isAssignCompanyModalOpen, setIsAssignCompanyModalOpen] =
    useState(false);
  const [selectedCompanies, setSelectedCompanies] =
    useState<TAssignCustomerToCompanyCredentials | null>(null);
  const [currentCustomer, setCurrentCustomer] = useState<TCustomer | null>(
    null,
  );

  const [isModalOpen, setIsModalOpen] = useState(false);
  const pathName = usePathname();
  const [params, setParams] = useState<Record<string, any>>({
    sort: "created_at",
  });
  const router = useRouter();
  const { data, isPending } = useCustomersInfiniteQuery(params);
  const { mutate: deleteCustomer } = useDeleteCustomerQuery(() =>
    setIsModalOpen(false),
  );
  const { mutate: assignSelectedCompanies } = useAssignCompany(
    currentCustomer?.id ?? "",
    () => {
      setIsAssignCompanyModalOpen(false);
    },
  );
  const columns = [
    "row",
    "full name",
    "email",
    "created at",
    "type",
    "status",
    "company",
    "role",
    "actions",
  ];
  const onConfirmDelete = () => {
    if (currentCustomer) {
      deleteCustomer(currentCustomer.id);
    }
  };
  const customers = data?.pages.flatMap((page) => page.data.customers) ?? [];
  return {
    allCustomers: customers,
    currentCustomer,
    columns,
    isPending,
    setCurrentCustomer,
    selectedCompanies,
    setSelectedCompanies,
    onConfirmDelete,
    setIsAssignCompanyModalOpen,
    isAssignCompanyModalOpen,
    assignSelectedCompanies,
    pathName,
    router,
    isModalOpen,
    setIsModalOpen,
  };
};

export default useCustomerListPresenter;
