"use client";
import {
  useCompanyCategoriesQuery,
  useCreateCompany,
  useUpdateCompany,
} from "@/hooks/queries";
import { ICreateCompanyCredentials } from "@/lib/api";
import { useIsMutating } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { SubmitHandler, useForm } from "react-hook-form";

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

const useCreateCompanyPresenter = ({ defaultValues, editMode, id }: IProps) => {
  const isMutating = useIsMutating();
  const {
    register,
    formState: { errors },
    handleSubmit,
    watch,
    setValue,
    reset,
  } = useForm<ICreateCompanyCredentials>({
    mode: "onChange",
    defaultValues: {
      ...defaultValues,
    },
  });

  useEffect(() => {
    if (defaultValues) {
      const categories = defaultValues?.tags?.categories?.map(
        (item: any) => item.id,
      );
      setValue("tags.categories", categories);
    }
  }, [defaultValues]);
  const router = useRouter();
  const { data: companyCategories } = useCompanyCategoriesQuery();
  const { mutate: createCompany, isPending: isCreating } = useCreateCompany();
  const { mutate: updateCompany, isPending: isUpdating } = useUpdateCompany(
    id as string,
  );
  const onSubmit: SubmitHandler<ICreateCompanyCredentials> = (data) => {
    const formattedData = {
      ...data,
      founded_year: data.founded_year ? +data.founded_year : 0,
      employee_count: data.employee_count ? +data.employee_count : 0,
      annual_revenue: data.annual_revenue ? +data.annual_revenue : 0,
      tags: {
        keywords: data?.tags?.keywords?.length ? data?.tags?.keywords : [],
        categories: data?.tags?.categories?.length
          ? data?.tags?.categories
          : [],
        cpv_codes: data?.tags?.cpv_codes?.length ? data?.tags?.cpv_codes : [],
        specializations: data?.tags?.specializations?.length
          ? data?.tags?.specializations
          : [],
        certifications: data?.tags?.certifications?.length
          ? data?.tags?.certifications
          : [],
      },
    };
    if (editMode) {
      updateCompany({
        id: id as string,
        credentials: formattedData as ICreateCompanyCredentials,
      });
    } else {
      createCompany(formattedData as ICreateCompanyCredentials);
    }

  };

  const handleCancel = () => {
    reset();
    router.back();
  };
  return {
    errors,
    register,
    handleSubmit,
    onSubmit,
    handleCancel,
    isMutating,
    isCreating,
    isUpdating,
    router,
    watch,
    setValue,
    companyCategories,
  };
};

export default useCreateCompanyPresenter;
