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

import { formHasAnyDirty, pickFormDirtyValues } from "@erp/core/client";
import {
  UnsavedChangesProvider,
  UpdateCommitButtonGroup,
  useHookForm,
  useUrlParamId,
} from "@erp/core/hooks";
import { showErrorToast, showSuccessToast, showWarningToast } from "@repo/rdx-ui/helpers";
import { FieldErrors, FormProvider } from "react-hook-form";
import {
  CustomerEditForm,
  CustomerEditorSkeleton,
  ErrorAlert,
  NotFoundCard,
} from "../../components";
import { useCustomerQuery, useUpdateCustomer } from "../../hooks";
import { useTranslation } from "../../i18n";
import { CustomerFormData, CustomerFormSchema, defaultCustomerFormData } from "../../schemas";

export const CustomerUpdatePage = () => {
  const customerId = useUrlParamId();
  const { t } = useTranslation();
  const navigate = useNavigate();

  // 1) Estado de carga del cliente (query)
  const {
    data: customerData,
    isLoading: isLoadingCustomer,
    isError: isLoadError,
    error: loadError,
  } = useCustomerQuery(customerId, { enabled: !!customerId });

  // 2) Estado de actualización (mutación)
  const {
    mutate,
    isPending: isUpdating,
    isError: isUpdateError,
    error: updateError,
  } = useUpdateCustomer();

  // 3) Form hook
  const form = useHookForm<CustomerFormData>({
    resolverSchema: CustomerFormSchema,
    initialValues: customerData ?? defaultCustomerFormData,
    disabled: isUpdating,
  });

  // 4) Submit con navegación condicionada por éxito
  const handleSubmit = (formData: CustomerFormData) => {
    const { dirtyFields } = form.formState;

    if (!formHasAnyDirty(dirtyFields)) {
      showWarningToast("No hay cambios para guardar");
      return;
    }

    const patchData = pickFormDirtyValues(formData, dirtyFields);
    mutate(
      { id: customerId!, data: patchData },
      {
        onSuccess(data) {
          showSuccessToast(t("pages.update.successTitle"), t("pages.update.successMsg"));

          // 🔹 limpiar el form e isDirty pasa a false
          form.reset(data);
        },
        onError(error) {
          showErrorToast(t("pages.update.errorTitle"), error.message);
        },
      }
    );
  };

  const handleReset = () => form.reset(customerData ?? defaultCustomerFormData);

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

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

  if (isLoadingCustomer) {
    return <CustomerEditorSkeleton />;
  }

  if (isLoadError) {
    return (
      <>
        <AppBreadcrumb />
        <AppContent>
          <ErrorAlert
            title={t("pages.update.loadErrorTitle", "No se pudo cargar el cliente")}
            message={
              (loadError as Error)?.message ??
              t("pages.update.loadErrorMsg", "Inténtalo de nuevo más tarde.")
            }
          />

          <div className='flex items-center justify-end'>
            <BackHistoryButton />
          </div>
        </AppContent>
      </>
    );
  }

  if (!customerData)
    return (
      <>
        <AppBreadcrumb />
        <AppContent>
          <NotFoundCard
            title={t("pages.update.notFoundTitle", "Cliente no encontrado")}
            message={t("pages.update.notFoundMsg", "Revisa el identificador o vuelve al listado.")}
          />
        </AppContent>
      </>
    );

  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.update.title")}
              </h2>
              <p className='text-muted-foreground scroll-m-20 tracking-tight text-balance'>
                {t("pages.update.description")}
              </p>
            </div>
            <UpdateCommitButtonGroup
              isLoading={isUpdating}
              disabled={isUpdating}
              cancel={{
                to: "/customers/list",
                disabled: isUpdating,
              }}
              submit={{
                formId: "customer-update-form",
                disabled: isUpdating,
              }}
              onBack={() => handleBack()}
              onReset={() => handleReset()}
            />
          </div>
          {/* Alerta de error de actualización (si ha fallado el último intento) */}
          {isUpdateError && (
            <ErrorAlert
              title={t("pages.update.errorTitle", "No se pudo guardar los cambios")}
              message={
                (updateError as Error)?.message ??
                t("pages.update.errorMsg", "Revisa los datos e inténtalo de nuevo.")
              }
            />
          )}

          <FormProvider {...form}>
            <CustomerEditForm
              formId={"customer-update-form"} // para que el botón del header pueda hacer submit
              onSubmit={handleSubmit}
              onError={handleError}
            />
          </FormProvider>
        </UnsavedChangesProvider>
      </AppContent>
    </>
  );
};
