import { useHookForm } from "@erp/core/hooks";
import { showErrorToast, showSuccessToast } from "@repo/rdx-ui/helpers";
import { useId } from "react";
import { FormProvider } from "react-hook-form";
import { useCreateCustomer } from "../../hooks";
import { useTranslation } from "../../i18n";
import {
  Customer,
  CustomerFormData,
  CustomerFormSchema,
  defaultCustomerFormData,
} from "../../schemas";

export interface UseCustomerCreateControllerOptions {
  onCreated?(created: Customer): void;
  successToasts?: boolean; // mostrar o no toast automáticcamente

  onError?(error: Error, data: CustomerFormData): void;
  errorToasts?: boolean; // mostrar o no toast automáticcamente
}

export const useCustomerCreateController = (options?: UseCustomerCreateControllerOptions) => {
  const { t } = useTranslation();
  const formId = useId(); // id único por instancia

  // 1) Estado de creación (mutación)
  const {
    mutateAsync,
    isPending: isCreating,
    isError: isCreateError,
    error: createError,
  } = useCreateCustomer();

  // 2) Form hook
  const form = useHookForm<CustomerFormData>({
    resolverSchema: CustomerFormSchema,
    initialValues: defaultCustomerFormData,
    disabled: isCreating,
  });

  /** Handlers */

  const resetForm = () => form.reset(defaultCustomerFormData);

  // Versión sincronizada
  const submitHandler = form.handleSubmit(async (formData) => {
    try {
      // Enviamos cambios al servidor
      const created = await mutateAsync({ data: formData });

      // Ha ido bien -> actualizamos form con datos reales
      // keepDirty = false -> deja el formulario sin cambios sin tener que esperar al siguiente render.
      form.reset(created, { keepDirty: false });

      console.log("form.formState =>", form.formState);

      if (options?.successToasts !== false) {
        showSuccessToast(
          t("pages.create.success.title", "Cliente creado"),
          t("pages.create.success.message", "Se ha creado correctamente.")
        );
      }
      options?.onCreated?.(created);
    } catch (err: unknown) {
      console.log("No se pudo crear el cliente.");

      // 1) Enfoca el primer error
      /*const firstKey = Object.keys(errors)[0] as keyof CustomerFormData | undefined;
        if (firstKey) {
          const el = document.querySelector<HTMLElement>(`[name="${String(firstKey)}"]`);
          el?.focus();
        }*/

      const error = err as Error;

      if (options?.errorToasts !== false) {
        showErrorToast(t("pages.update.error.title"), error.message);
      }
      options?.onError?.(error, formData);
    }
  });

  // Evento onSubmit ya preparado para el <form>
  const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.stopPropagation(); // <-- evita que el submit se propage por los padre en el árbol DOM
    submitHandler(event);
  };

  return {
    // form
    form,
    formId,

    // handlers del form
    onSubmit,
    resetForm,

    // mutation
    isCreating,
    isCreateError,
    createError,

    // Por comodidad
    FormProvider,
  };
};
