"use client";

import {
  useCompanyFullList,
  useCreateCustomer,
  useUpdateCustomer,
} from "@/hooks/queries";
import { CreateCustomerCredentials } from "@/lib/api";
import { useRouter } from "next/navigation";
import { SubmitHandler, useForm } from "react-hook-form";

interface IProps {
  editMode?: boolean;
  defaultValues?: CreateCustomerCredentials;
  id?: string;
}

const useCreateCustomerPresenter = ({
  defaultValues,
  editMode,
  id,
}: IProps) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<CreateCustomerCredentials>({
    mode: "onChange",
    defaultValues,
  });
  const router = useRouter();
  const { mutate: createCustomer, isPending: isCreating } = useCreateCustomer();
  const { mutate: updateCustomer, isPending: isUpdating } = useUpdateCustomer(
    id as string,
  );
  const { data: companies } = useCompanyFullList();
  const onSubmit: SubmitHandler<CreateCustomerCredentials> = (data) => {
    if (editMode) {
      updateCustomer({
        id: id as string,
        credentials: data,
      });
    } else {

      createCustomer({
        ...data,
        employee_count: data.employee_count ? +data.employee_count : undefined,
        annual_revenue: data.annual_revenue ? +data.annual_revenue : undefined,
        founded_year: data.founded_year ? +data.founded_year : undefined,
      });
    }
  };
  return {
    handleSubmit,
    register,
    errors,
    onSubmit,
    companies: companies?.data.companies,
    router,
  };
};

export default useCreateCustomerPresenter;
