import { AppContent, AppHeader, BackHistoryButton } from "@repo/rdx-ui/components";

import { PageHeader } from '@erp/core/components';
import {
  UnsavedChangesProvider,
  UpdateCommitButtonGroup,
  useUrlParamId
} from "@erp/core/hooks";
import {
  CustomerEditForm,
  CustomerEditorSkeleton,
  ErrorAlert,
  NotFoundCard,
} from "../../components";
import { useTranslation } from "../../i18n";
import { useCustomerUpdateController } from './use-customer-update-controller';

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

  const {
    form, formId, onSubmit, resetForm,

    customerData,
    isLoading, isLoadError, loadError,

    isUpdating, isUpdateError, updateError,

    FormProvider
  } = useCustomerUpdateController(customerId, {});

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

  if (isLoadError) {
    return (
      <>

        <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 (
      <>

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

  return (
    <UnsavedChangesProvider isDirty={form.formState.isDirty}>
      <AppHeader>
        <PageHeader
          backIcon
          title={t("pages.update.title")}
          description={t("pages.update.description")}
          rightSlot={
            <UpdateCommitButtonGroup
              isLoading={isUpdating}
              disabled={isUpdating}
              cancel={{
                formId,
                to: "/customers/list",
                disabled: isUpdating,
              }}
              submit={{
                formId,
                disabled: isUpdating,
              }}
              onReset={resetForm}
            />
          }
        />
      </AppHeader>
      <AppContent>
        {/* 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={formId} // para que el botón del header pueda hacer submit
            onSubmit={onSubmit}
            className="bg-white rounded-xl border shadow-xl max-w-7xl mx-auto mt-6"
          />
        </FormProvider>

      </AppContent>
    </UnsavedChangesProvider>
  );
};
