import { ErrorAlert, NotFoundCard, PageHeader } from "@erp/core/components";
import { UnsavedChangesProvider, UpdateCommitButtonGroup, useUrlParamId } from "@erp/core/hooks";
import { AppContent, AppHeader, BackHistoryButton } from "@repo/rdx-ui/components";

import { useTranslation } from "../../../i18n";
import { useCustomerUpdateController } from "../../controllers";
import { CustomerEditorSkeleton } from "../components";
import { CustomerEditForm } from "../editor";

export const CustomerUpdatePage = () => {
  const initialCustomerId = useUrlParamId();
  const { t } = useTranslation();

  const {
    form,
    formId,
    onSubmit,
    resetForm,

    customerData,
    isLoading,
    isLoadError,
    loadError,

    isUpdating,
    isUpdateError,
    updateError,

    FormProvider,
  } = useCustomerUpdateController(initialCustomerId, {});

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

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

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

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

  return (
    <UnsavedChangesProvider isDirty={false}>
      <AppHeader>
        <PageHeader
          backIcon
          description={t("pages.update.description")}
          rightSlot={
            <UpdateCommitButtonGroup
              cancel={{
                formId,
                to: "/customers/list",
                disabled: isUpdating,
              }}
              disabled={isUpdating}
              isLoading={isUpdating}
              onReset={resetForm}
              submit={{
                formId,
                disabled: isUpdating,
              }}
            />
          }
          title={t("pages.update.title")}
        />
      </AppHeader>
      <AppContent>
        {/* Alerta de error de actualización (si ha fallado el último intento) */}
        {isUpdateError && (
          <ErrorAlert
            message={
              (updateError as Error)?.message ??
              t("pages.update.errorMsg", "Revisa los datos e inténtalo de nuevo.")
            }
            title={t("pages.update.errorTitle", "No se pudo guardar los cambios")}
          />
        )}

        <FormProvider {...form}>
          <CustomerEditForm
            className="bg-white rounded-xl border shadow-xl max-w-7xl mx-auto mt-6 " // para que el botón del header pueda hacer submit
            formId={formId}
            onSubmit={onSubmit}
          />
        </FormProvider>
      </AppContent>
    </UnsavedChangesProvider>
  );
};
