import { AppBreadcrumb, AppContent } from "@repo/rdx-ui/components";
import { useNavigate } from "react-router-dom";

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

export const CustomerCreatePage = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();

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

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

  // 3) Submit con navegación condicionada por éxito
  const handleSubmit = (formData: CustomerFormData) => {
    mutate(
      { data: formData },
      {
        onSuccess(data) {
          showSuccessToast(t("pages.create.successTitle"), t("pages.create.successMsg"));

          // 🔹 limpiar el form e isDirty pasa a false
          form.reset(defaultCustomerFormData);

          navigate("/customers/list", {
            state: { customerId: data.id, isNew: true },
            replace: true,
          });
        },
        onError(error) {
          showErrorToast(t("pages.create.errorTitle"), error.message);
        },
      }
    );
  };

  const handleError = (errors: FieldErrors<CustomerFormData>) => {
    console.error("Errores en el formulario:", errors);
    // Aquí puedes manejar los errores, por ejemplo, mostrar un mensaje al usuario
  };

  const handleBack = () => {
    navigate(-1);
  };

  return (
    <>
      <AppBreadcrumb />
      <AppContent>
        <UnsavedChangesProvider isDirty={form.formState.isDirty}>
          <div className='flex items-center justify-between space-y-6'>
            <div className='space-y-2'>
              <h2 className='text-2xl font-bold tracking-tight text-balance scroll-m-2'>
                {t("pages.create.title")}
              </h2>
              <p className='text-muted-foreground scroll-m-20 tracking-tight text-balance'>
                {t("pages.create.description")}
              </p>
            </div>
            <UpdateCommitButtonGroup
              isLoading={isCreating}
              disabled={isCreating}
              cancel={{
                to: "/customers/list",
                disabled: isCreating,
              }}
              submit={{
                formId: "customer-create-form",
                disabled: isCreating,
              }}
              onBack={() => handleBack()}
            />
          </div>
          {/* Alerta de error de actualización (si ha fallado el último intento) */}
          {isCreateError && (
            <ErrorAlert
              title={t("pages.create.errorTitle", "No se pudo guardar los cambios")}
              message={
                (createError as Error)?.message ??
                t("pages.create.errorMsg", "Revisa los datos e inténtalo de nuevo.")
              }
            />
          )}

          <FormProvider {...form}>
            <CustomerEditForm
              formId='customer-create-form'
              onSubmit={handleSubmit}
              onError={handleError}
            />
          </FormProvider>
        </UnsavedChangesProvider>
      </AppContent>
    </>
  );
};
