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 {
  CustomerInvoiceEditorSkeleton
} from "../../components";
import { InvoiceProvider } from '../../context';
import { useInvoiceQuery } from "../../hooks";
import { useTranslation } from "../../i18n";
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;

  console.log("InvoiceUpdatePage");

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

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

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

