"use client";

import {
  useAssignCompany,
  useCustomersInfiniteQuery,
  useDeleteCustomerQuery,
} from "@/hooks/queries";
import { TAssignCustomerToCompanyCredentials, TCustomer } from "@/lib/api";
import { deleteEmptyKeys } from "@/utils/shared";
import { useIsMutating } from "@tanstack/react-query";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";

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

  const [isModalOpen, setIsModalOpen] = useState(false);
  const pathName = usePathname();
  const searchParams = useSearchParams();
  const [params, setParams] = useState<Record<string, any>>({});
  const router = useRouter();
  const isMutating = useIsMutating();

  const {
    register: filterRegister,
    handleSubmit: handleFilterSubmit,
    reset: filterFormReset,
    watch,
    setValue: setFilterValue,
  } = useForm();

  useEffect(() => {
    const newParams: Record<string, any> = {
      sort: "created_at",
    };
    for (const [key, value] of searchParams.entries()) {
      newParams[key] = value;
    }
    setParams(newParams);
    filterFormReset(newParams);
  }, [searchParams, filterFormReset]);

  const { data, isPending } = useCustomersInfiniteQuery(params);
  const { mutate: deleteCustomer } = useDeleteCustomerQuery(() =>
    setIsModalOpen(false),
  );
  const { mutate: assignSelectedCompanies } = useAssignCompany(
    currentCustomer?.id ?? "",
    () => {
      setIsAssignCompanyModalOpen(false);
    },
  );

  const search = (data: any) => {
    const newParams = { ...params, ...data };
    const cleanedParams = deleteEmptyKeys(newParams);
    const queryString = new URLSearchParams(cleanedParams).toString();
    router.push(`${pathName}?${queryString}`);
    setIsFilterModalOpen(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,
    isFilterModalOpen,
    setIsFilterModalOpen,
    filterRegister,
    handleFilterSubmit,
    search,
    watch,
    setFilterValue,
    isMutating,
  };
};

export default useCustomerListPresenter;
