import { useModal } from '@admin/components/ui/modal';
import { router } from '@inertiajs/react';
import { useState } from 'react';
import { usePage } from '@inertiajs/react';
import ContactAddModal from './contact-add-modal';

interface Contact {
    id: number;
    name: string;
    email: string;
    phone: string | null;
    user_id: number | null;
    created_at: string | null;
}

interface ContactModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    contact: Contact | null;
    onSuccess: () => void;
}

export function ContactModal({ open, onOpenChange, contact, onSuccess }: ContactModalProps) {
    const [isLoading, setIsLoading] = useState(false);
    const { props } = usePage<any>();
    const externalErrors = (props?.errors ?? {}) as Record<string, string | string[]>;

    const handleSubmit = async (values: any) => {
        setIsLoading(true);
        try {
            if (contact) {
                // Edit existing contact
                const submitData: any = { ...values, _method: 'put' };
                router.post(route('contacts.update', { contact: contact.id }), submitData, {
                    onSuccess: () => {
                        // Notify parent + global listeners to refresh
                        onSuccess();
                        try {
                            window.dispatchEvent(new CustomEvent('contacts:refresh', { detail: { action: 'updated' } }));
                        } catch {}
                        onOpenChange(false);
                    },
                    onError: (errors) => {
                        console.error('Error updating contact:', errors);
                    },
                    onFinish: () => setIsLoading(false),
                });
            } else {
                // Create new contact
                router.post(route('contacts.store'), values, {
                    onSuccess: () => {
                        // Notify parent + global listeners to refresh
                        onSuccess();
                        try {
                            window.dispatchEvent(new CustomEvent('contacts:refresh', { detail: { action: 'created' } }));
                        } catch {}
                        onOpenChange(false);
                    },
                    onError: (errors) => {
                        console.error('Error creating contact:', errors);
                    },
                    onFinish: () => setIsLoading(false),
                });
            }
        } catch (error) {
            console.error('Error submitting contact:', error);
            setIsLoading(false);
        }
    };

    return (
        <ContactAddModal
            isOpen={open}
            setIsOpen={onOpenChange}
            mode={contact ? 'edit' : 'add'}
            initialContact={contact}
            onSubmit={handleSubmit}
            externalErrors={externalErrors}
        />
    );
}
