import React, {useState} from 'react';
import {usePage} from '@inertiajs/react';
import {makePostRequest, makePutRequest} from '@/lib/request';
import toast from 'react-hot-toast';

interface CreateProps {
    open: boolean;
    onClose: () => void;
    // when provided the component acts in "edit" mode and will update the client
    client?: any;
    mode?: 'create' | 'edit';
}

export default function Create({ open, onClose, client, mode = 'create' }: CreateProps): JSX.Element | null {
    const { auth } = usePage<{ auth: { user: any } }>().props;
    const token = auth?.user?.token ?? auth?.user?.api_token ?? undefined;

    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [phone, setPhone] = useState('');
    const [clientType, setClientType] = useState('individual');
    const [status] = useState('prospective');
    const [submitting, setSubmitting] = useState(false);
    const [errors, setErrors] = useState<Record<string, string[]>>({});

    const closeOverlay = () => {
        // notify parent to close modal
        onClose();
    };

    // When editing, populate fields from the provided client
    React.useEffect(() => {
        if (client && mode === 'edit') {
            setName(client.name ?? '');
            setEmail(client.email ?? '');
            setPhone(client.phone ?? '');
            setClientType(client.client_type ?? client.clientType ?? 'individual');
        } else if (!open) {
            // reset when closed
            setName('');
            setEmail('');
            setPhone('');
            setClientType('individual');
            setErrors({});
        }
        // only run when client, mode or open changes
    }, [client, mode, open]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setErrors({});

        // Basic client-side validation
        const clientErrors: Record<string, string[]> = {};
        if (!name.trim()) clientErrors.name = ['Name is required'];
        if (!clientType) clientErrors.client_type = ['Client type is required'];
        if (Object.keys(clientErrors).length) {
            setErrors(clientErrors);
            return;
        }

        setSubmitting(true);
        try {
            const payload = {
                name: name.trim(),
                email: email.trim() || null,
                phone: phone.trim() || null,
                client_type: clientType,
                status,
            };

            if (mode === 'edit' && client?.id) {
                // update existing client
                const { data } = await makePutRequest(`/api/clients/${client.id}`, payload, { token });
                toast.success('Client updated');
                window.dispatchEvent(new CustomEvent('client:updated', { detail: data.result }));
            } else {
                const { data } = await makePostRequest('/api/clients', payload, { token });
                toast.success('Client created');
                // Emit a DOM event so other parts of the app can react (e.g., refresh list)
                window.dispatchEvent(new CustomEvent('client:created', { detail: data.result }));
            }

            // Close modal
            closeOverlay();
        } catch (err: any) {
            // Handle validation errors from server (Laravel 422)
            const resp = err?.response?.data;
            if (resp && resp.errors) {
                setErrors(resp.errors);
            } else {
                toast.error('Failed to create client');
            }
        } finally {
            setSubmitting(false);
        }
    };

    if (!open) return null;

    return (
        <div role="dialog" aria-modal="true" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
            <div className="bg-white rounded-xl shadow-xl w-full max-w-md">
                <form className="space-y-3" onSubmit={handleSubmit} noValidate>
                    <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200">
                        <h3 className="text-base font-semibold text-gray-800">{mode === 'edit' ? 'Edit Client' : 'Add Client'}</h3>
                        <button
                            type="button"
                            className="p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors"
                            onClick={closeOverlay}
                            aria-label="Close"
                        >
                            <i className="ri ri-close-line text-lg"></i>
                        </button>
                    </div>

                    <div className="px-5 py-5 space-y-4">
                        <div>
                            <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">Name</label>
                            <input
                                id="name"
                                type="text"
                                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                                placeholder="Client name"
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                            />
                            {errors.name && <p className="text-sm text-red-600">{errors.name[0]}</p>}
                        </div>

                        <div>
                            <label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">Email</label>
                            <input
                                id="email"
                                type="email"
                                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                                placeholder="Email (optional)"
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                            />
                            {errors.email && <p className="text-sm text-red-600">{errors.email[0]}</p>}
                        </div>

                        <div>
                            <label htmlFor="phone" className="block text-sm font-medium text-gray-700 mb-1">Phone</label>
                            <input
                                id="phone"
                                type="text"
                                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                                placeholder="Phone (optional)"
                                value={phone}
                                onChange={(e) => setPhone(e.target.value)}
                            />
                            {errors.phone && <p className="text-sm text-red-600">{errors.phone[0]}</p>}
                        </div>

                        <div>
                            <label htmlFor="clientType" className="block text-sm font-medium text-gray-700 mb-1">Client Type</label>
                            <select
                                id="clientType"
                                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                                value={clientType}
                                onChange={(e) => setClientType(e.target.value)}
                            >
                                <option value="individual">Individual</option>
                                <option value="corporate">Corporate</option>
                                <option value="government">Government</option>
                            </select>
                            {errors.client_type && (
                                <p className="text-sm text-red-600">{errors.client_type[0]}</p>
                            )}
                        </div>
                    </div>

                    <div className="flex items-center justify-end gap-2 px-5 py-4 border-t border-gray-200">
                        <button
                            type="button"
                            onClick={closeOverlay}
                            className="px-4 py-2 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                        >
                            Cancel
                        </button>
                        <button
                            type="submit"
                            className="flex items-center gap-1.5 px-4 py-2 text-sm bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-60 transition-colors font-medium"
                            disabled={submitting}
                        >
                            {submitting ? (
                                <>
                                    <span className="animate-spin h-3 w-3 border-2 border-white border-t-transparent rounded-full inline-block"></span>
                                    {mode === 'edit' ? 'Saving…' : 'Creating…'}
                                </>
                            ) : (
                                (mode === 'edit' ? 'Save' : 'Create')
                            )}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}
