import { ErrorAlert, NotFoundCard, PageHeader } from "@erp/core/components";
import { UnsavedChangesProvider, UpdateCommitButtonGroup } from "@erp/core/hooks";
import { AppContent, AppHeader, BackHistoryButton } from "@repo/rdx-ui/components";
import { Spinner } from "@repo/shadcn-ui/components";
import { FormProvider } from "react-hook-form";

import { useTranslation } from "../../../i18n";
import { useCustomerUpdatePageController } from "../../controllers";
import { CustomerEditorSkeleton } from "../components";
import { CustomerUpdateEditorForm } from "../editor";

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

  const { updateCtrl } = useCustomerUpdatePageController();

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

  if (updateCtrl.isLoadError) {
    return (
      <AppContent>
        <ErrorAlert
          message={
            updateCtrl.loadError instanceof Error
              ? updateCtrl.loadError.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 (!updateCtrl.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={updateCtrl.form.formState.isDirty}>
      <AppHeader className="space-y-4 max-w-5xl mx-auto">
        <PageHeader
          backIcon
          description={t("pages.update.description")}
          rightSlot={
            <UpdateCommitButtonGroup
              cancel={{
                formId: updateCtrl.formId,
                to: "/customers/list",
                disabled: updateCtrl.isUpdating,
              }}
              disabled={updateCtrl.isUpdating}
              isLoading={updateCtrl.isUpdating}
              onReset={updateCtrl.resetForm}
              submit={{
                formId: updateCtrl.formId,
                disabled: updateCtrl.isUpdating,
              }}
            />
          }
          title={t("pages.update.title")}
        />
      </AppHeader>
      <AppContent className="space-y-4 max-w-5xl mx-auto">
        {/* Alerta de error de actualización (si ha fallado el último intento) */}
        {updateCtrl.isUpdateError && (
          <ErrorAlert
            message={
              (updateCtrl.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")}
          />
        )}

        {updateCtrl.isLoading && <Spinner />}

        {!updateCtrl.isLoading && (
          <FormProvider {...updateCtrl.form}>
            <CustomerUpdateEditorForm
              formId={updateCtrl.formId}
              isSubmitting={updateCtrl.isUpdating}
              onReset={updateCtrl.resetForm}
              onSubmit={updateCtrl.onSubmit}
            />
          </FormProvider>
        )}
      </AppContent>
    </UnsavedChangesProvider>
  );
};
