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

import { PageHeader } from '@erp/core/components';
import { UnsavedChangesProvider, UpdateCommitButtonGroup } from "@erp/core/hooks";
import { CustomerEditForm, ErrorAlert } from "../../components";
import { useTranslation } from "../../i18n";
import { useCustomerCreateController } from './use-customer-create-controller';

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

  const {
    form, formId, onSubmit, resetForm,

    isCreating, isCreateError, createError,

    FormProvider
  } = useCustomerCreateController({
    onCreated: (created) =>
      navigate("/customers/list", { state: { customerId: created.id, isNew: true }, replace: true })
  });


  return (
    <UnsavedChangesProvider isDirty={form.formState.isDirty}>
      <AppHeader>
        <PageHeader
          backIcon
          title={t("pages.create.title")}
          description={t("pages.create.description")}
          rightSlot={
            <UpdateCommitButtonGroup
              isLoading={isCreating}
              disabled={isCreating}
              cancel={{
                to: "/customers/list",
                disabled: isCreating,
              }}
              submit={{
                formId: formId,
                disabled: isCreating,
              }}
              onReset={resetForm}
            />
          }
        />
      </AppHeader>
      <AppContent>
        {/* 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={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>
  );
};
