import { router, useHttp } from '@inertiajs/react';
import { Save } from 'lucide-react';
import { type ReactNode, useEffect } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { update as seccionUpdate } from '@/routes/ficha/seccion';
import { SectionFormProvider } from '../lib/section-form-context';
import type { SeccionCodigo } from '../sections';

type Props = {
    fichaId: number;
    seccion: SeccionCodigo;
    data: Record<string, any>;
    onDirtyChange: (dirty: boolean) => void;
    children: ReactNode;
};

/**
 * Se remonta por `key` al cambiar de sección, garantizando que
 * `useHttp(data)` se inicialice limpio con los datos de la sección actual
 * y que no queden handlers ni peticiones en vuelo de la sección anterior.
 */
export function SectionFormBoundary({
    fichaId,
    seccion,
    data,
    onDirtyChange,
    children,
}: Props) {
    const form = useHttp(data);

    useEffect(() => {
        onDirtyChange(form.isDirty);
    }, [form.isDirty, onDirtyChange]);

    const handleSave = () => {
        form.patch(seccionUpdate.url({ ficha: fichaId, seccion }), {
            onSuccess: () => {
                form.setDefaults();
                router.reload({ only: ['secciones_completas'] });
                toast.success('Sección guardada');
            },
            onError: () => toast.error('Revisa los campos marcados'),
        });
    };

    return (
        <SectionFormProvider form={form}>
            <main className="min-h-0 flex-1 overflow-y-auto p-6">
                {children}
            </main>

            <footer className="flex shrink-0 items-center justify-end gap-3 border-t bg-background px-6 py-3">
                <span className="text-xs text-muted-foreground">
                    {form.isDirty ? 'Cambios sin guardar' : 'Todo guardado'}
                </span>
                <Button
                    size="sm"
                    disabled={form.processing || !form.isDirty}
                    onClick={handleSave}
                >
                    <Save data-icon="inline-start" />
                    {form.processing ? 'Guardando…' : 'Guardar'}
                </Button>
            </footer>
        </SectionFormProvider>
    );
}
