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


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, defaultCustomerInvoiceFormData])

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


    const handleSubmit = (formData: InvoiceFormData) => {
        mutate(
            { id: invoice_id, data: formData },
            {
                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
    };

    console.log("InvoiceUpdateComp")

    return (
        <UnsavedChangesProvider isDirty={form.formState.isDirty}>
            <AppHeader>
                <AppBreadcrumb />
                <PageHeader
                    title={`${t("pages.edit.title")} ${invoiceData.invoice_number}`}
                    icon={<FilePenIcon className='size-6 text-primary' aria-hidden />}
                    rightSlot={
                        <FormCommitButtonGroup
                            isLoading={isPending}
                            submit={{ formId: "invoice-update-form", disabled: isPending }}
                            cancel={{ to: "/customer-invoices/list" }}
                            onBack={() => navigate(-1)}
                        />
                    }
                />
            </AppHeader>

            <AppContent>
                <FormProvider {...form}>

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