import { PageHeader } from '@erp/core/components';
import {
    UnsavedChangesProvider,
    UpdateCommitButtonGroup,
    useHookForm
} from "@erp/core/hooks";
import { AppContent, AppHeader } from "@repo/rdx-ui/components";
import { showErrorToast, showSuccessToast } from "@repo/rdx-ui/helpers";
import { useMemo } from 'react';
import { FieldErrors, FormProvider } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { useInvoiceContext } from '../../context';
import { useUpdateCustomerInvoice } from "../../hooks";
import { useTranslation } from "../../i18n";
import {
    CustomerInvoice,
    InvoiceFormData,
    InvoiceFormSchema,
    defaultCustomerInvoiceFormData,
    invoiceDtoToFormAdapter
} from "../../schemas";
import { InvoiceUpdateForm } from './invoice-update-form';


export type InvoiceUpdateCompProps = {
    invoice: CustomerInvoice,
}

export const InvoiceUpdateComp = ({
    invoice: invoiceData,
}: InvoiceUpdateCompProps) => {
    const { t } = useTranslation();
    const navigate = useNavigate();
    const { invoice_id } = useInvoiceContext(); // ahora disponible desde el inicio
    const context = useInvoiceContext();

    const isPending = !invoiceData;

    const {
        mutate,
        isPending: isUpdating,
        isError: isUpdateError,
        error: updateError,
    } = useUpdateCustomerInvoice();

    const initialValues = useMemo(() => {
        return invoiceData
            ? invoiceDtoToFormAdapter.fromDto(invoiceData, context)
            : defaultCustomerInvoiceFormData
    }, [invoiceData, context]);


    const form = useHookForm<InvoiceFormData>({
        resolverSchema: InvoiceFormSchema,
        initialValues,
        disabled: !invoiceData || isUpdating
    });

    const handleSubmit = (formData: InvoiceFormData) => {
        const dto = invoiceDtoToFormAdapter.toDto(formData, context)
        console.log("dto => ", dto);
        mutate(
            { id: invoice_id, data: dto as Partial<InvoiceFormData> },
            {
                onSuccess: () => showSuccessToast(t("pages.update.successTitle")),
                onError: (e) => showErrorToast(t("pages.update.errorTitle"), e.message),
            }
        );
    };

    const handleReset = () =>
        form.reset((invoiceData as unknown as InvoiceFormData) ?? defaultCustomerInvoiceFormData);

    const handleBack = () => {
        navigate(-1);
    };

    const handleError = (errors: FieldErrors<InvoiceFormData>) => {
        console.error("Errores en el formulario:", errors);
        // Aquí puedes manejar los errores, por ejemplo, mostrar un mensaje al usuario
    };

    return (
        <UnsavedChangesProvider isDirty={form.formState.isDirty}>
            <AppHeader>
                <PageHeader
                    title={`${t("pages.edit.title")} ${invoiceData.invoice_number}`}
                    rightSlot={
                        <UpdateCommitButtonGroup
                            isLoading={isPending}

                            submit={{ formId: "invoice-update-form", variant: 'default', disabled: isPending, label: t("pages.edit.actions.save_draft") }}
                            cancel={{ to: "/customer-invoices/list" }}
                            onBack={() => navigate(-1)}
                        />



                    }
                />
            </AppHeader>

            <AppContent>
                <FormProvider {...form}>
                    <InvoiceUpdateForm
                        formId="invoice-update-form"
                        onSubmit={handleSubmit}
                        onError={handleError}
                        className="max-w-full"
                    />
                </FormProvider>
            </AppContent>
        </UnsavedChangesProvider>
    );
};