import { SpainTaxCatalogProvider } from "@erp/core";
import { useUrlParamId } from "@erp/core/hooks";
import { ErrorAlert } from "@erp/customers/components";
import { AppContent, BackHistoryButton } from "@repo/rdx-ui/components";
import { useMemo } from "react";

import { InvoiceProvider } from "../../context";
import { useInvoiceQuery } from "../../hooks";
import { useTranslation } from "../../i18n";
import { CustomerInvoiceEditorSkeleton } from "../../shared/ui/components";

import { InvoiceUpdateComp } from "./invoice-update-comp";

export const InvoiceUpdatePage = () => {
  const invoice_id = useUrlParamId();
  const { t } = useTranslation();
  const taxCatalog = useMemo(() => SpainTaxCatalogProvider(), []);

  const invoiceQuery = useInvoiceQuery(invoice_id, { enabled: !!invoice_id });
  const { data: invoiceData, isLoading, isError, error } = invoiceQuery;

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

  if (isError || !invoiceData) {
    return (
      <AppContent>
        <ErrorAlert
          message={(error as Error)?.message || "Error al cargar la factura"}
          title={t("pages.update.loadErrorTitle")}
        />
        <BackHistoryButton />
      </AppContent>
    );
  }

  // Monta el contexto aquí, así todo lo que esté dentro puede usar hooks
  return (
    <InvoiceProvider
      company_id={invoiceData.company_id}
      currency_code={invoiceData.currency_code}
      invoice_id={invoice_id!}
      language_code={invoiceData.language_code}
      status={invoiceData.status}
      taxCatalog={taxCatalog}
    >
      <InvoiceUpdateComp invoice={invoiceData} />
    </InvoiceProvider>
  );
};
