import { usePage } from '@inertiajs/react';
import { useForm } from '@inertiajs/react';
import { useEffect, useState, useRef, useLayoutEffect, useCallback } from 'react';
import { toast, Toaster } from 'react-hot-toast';
import { formatPriceTriple, formatPriceTripleObject } from '@/utils/priceFormatter';

export default function Reservation({ accommodations = [], eventRooms = [] }) {
    const { flash, turnstileSiteKey, siteinfo } = usePage().props;
    const [numberOfAdults, setNumberOfAdults] = useState(1);
    const [numberOfChildren, setNumberOfChildren] = useState(0);
    const [numberOfRooms, setNumberOfRooms] = useState(1); // for event/conference rooms only
    const [calculatedPrice, setCalculatedPrice] = useState({ bifPrice: 0, usdPrice: 0, eurPrice: 0, combined: '0 BIF | 0 USD | 0 EUR' });
    const [bookingType, setBookingType] = useState('accommodation');
    const [turnstileReady, setTurnstileReady] = useState(false);
    const [currentLang, setCurrentLang] = useState('en');
    const isInitializingFromUrl = useRef(false);
    const initialBookableIdFromUrl = useRef(null);
    const [scriptsReady, setScriptsReady] = useState(false);
    const datePickersInitialized = useRef(false);

    // Translation strings for all supported languages
    const translations = {
        en: {
            name: 'Name',
            phone: 'Phone',
            email: 'Email',
            bookingType: 'Booking Type',
            accommodation: 'Accommodation',
            eventRoom: 'Event Room',
            selectAccommodation: 'Select Accommodation',
            selectEventRoom: 'Select Event Room',
            checkIn: 'Check In',
            checkOut: 'Check Out',
            selectRoomNumber: 'Select Room Number',
            selectRoom: 'Select a room number',
            noRoomsAvailable: 'No rooms available for the selected dates. Please choose different dates.',
            loadingRooms: 'Loading available rooms...',
            eventStartDate: 'Event Start Date',
            eventEndDate: 'Event End Date',
            eventStartTime: 'Event Start Time',
            eventEndTime: 'Event End Time',
            adults: 'Adults',
            children: 'Children',
            numberOfRooms: 'Number of rooms',
            estimatedPrice: 'Estimated Price',
            notes: 'Notes',
            loadingCaptcha: 'Loading CAPTCHA...',
            reserveNow: 'Reserve Now',
            processing: 'Processing...',
            perNight: '/night',
            required: '*',
        },
        fr: {
            name: 'Nom',
            phone: 'Téléphone',
            email: 'Email',
            bookingType: 'Type de réservation',
            accommodation: 'Hébergement',
            eventRoom: 'Salle de réception',
            selectAccommodation: 'Sélectionner un hébergement',
            selectEventRoom: 'Sélectionner une salle',
            checkIn: 'Arrivée',
            checkOut: 'Départ',
            selectRoomNumber: 'Sélectionner le numéro de chambre',
            selectRoom: 'Sélectionner un numéro de chambre',
            noRoomsAvailable: 'Aucune chambre disponible pour les dates sélectionnées. Veuillez choisir des dates différentes.',
            loadingRooms: 'Chargement des chambres disponibles...',
            eventStartDate: 'Date de début',
            eventEndDate: 'Date de fin',
            eventStartTime: 'Heure de début',
            eventEndTime: 'Heure de fin',
            adults: 'Adultes',
            children: 'Enfants',
            numberOfRooms: 'Nombre de salles',
            estimatedPrice: 'Prix estimé',
            notes: 'Notes',
            loadingCaptcha: 'Chargement CAPTCHA...',
            reserveNow: 'Réserver maintenant',
            processing: 'Traitement...',
            perNight: '/nuit',
            required: '*',
        },
        de: {
            name: 'Name',
            phone: 'Telefon',
            email: 'E-Mail',
            bookingType: 'Buchungstyp',
            accommodation: 'Unterkunft',
            eventRoom: 'Veranstaltungsraum',
            selectAccommodation: 'Unterkunft auswählen',
            selectEventRoom: 'Veranstaltungsraum auswählen',
            checkIn: 'Anreise',
            checkOut: 'Abreise',
            selectRoomNumber: 'Zimmernummer auswählen',
            selectRoom: 'Zimmernummer auswählen',
            noRoomsAvailable: 'Keine Zimmer für die ausgewählten Daten verfügbar. Bitte wählen Sie andere Daten.',
            loadingRooms: 'Verfügbare Zimmer werden geladen...',
            eventStartDate: 'Startdatum',
            eventEndDate: 'Enddatum',
            eventStartTime: 'Startzeit',
            eventEndTime: 'Endzeit',
            adults: 'Erwachsene',
            children: 'Kinder',
            numberOfRooms: 'Anzahl der Räume',
            estimatedPrice: 'Geschätzter Preis',
            notes: 'Notizen',
            loadingCaptcha: 'CAPTCHA wird geladen...',
            reserveNow: 'Jetzt reservieren',
            processing: 'Verarbeitung...',
            perNight: '/Nacht',
            required: '*',
        },
        it: {
            name: 'Nome',
            phone: 'Telefono',
            email: 'Email',
            bookingType: 'Tipo di prenotazione',
            accommodation: 'Alloggio',
            eventRoom: 'Sala eventi',
            selectAccommodation: 'Seleziona alloggio',
            selectEventRoom: 'Seleziona sala',
            checkIn: 'Check-in',
            checkOut: 'Check-out',
            selectRoomNumber: 'Seleziona numero camera',
            selectRoom: 'Seleziona un numero di camera',
            noRoomsAvailable: 'Nessuna camera disponibile per le date selezionate. Si prega di scegliere date diverse.',
            loadingRooms: 'Caricamento camere disponibili...',
            eventStartDate: 'Data inizio',
            eventEndDate: 'Data fine',
            eventStartTime: 'Ora inizio',
            eventEndTime: 'Ora fine',
            adults: 'Adulti',
            children: 'Bambini',
            numberOfRooms: 'Numero di sale',
            estimatedPrice: 'Prezzo stimato',
            notes: 'Note',
            loadingCaptcha: 'Caricamento CAPTCHA...',
            reserveNow: 'Prenota ora',
            processing: 'Elaborazione...',
            perNight: '/notte',
            required: '*',
        },
        es: {
            name: 'Nombre',
            phone: 'Teléfono',
            email: 'Email',
            bookingType: 'Tipo de reserva',
            accommodation: 'Alojamiento',
            eventRoom: 'Sala de eventos',
            selectAccommodation: 'Seleccionar alojamiento',
            selectEventRoom: 'Seleccionar sala',
            checkIn: 'Entrada',
            checkOut: 'Salida',
            selectRoomNumber: 'Seleccionar número de habitación',
            selectRoom: 'Seleccione un número de habitación',
            noRoomsAvailable: 'No hay habitaciones disponibles para las fechas seleccionadas. Por favor, elija fechas diferentes.',
            loadingRooms: 'Cargando habitaciones disponibles...',
            eventStartDate: 'Fecha de inicio',
            eventEndDate: 'Fecha de finalización',
            eventStartTime: 'Hora de inicio',
            eventEndTime: 'Hora de finalización',
            adults: 'Adultos',
            children: 'Niños',
            numberOfRooms: 'Número de salas',
            estimatedPrice: 'Precio estimado',
            notes: 'Notas',
            loadingCaptcha: 'Cargando CAPTCHA...',
            reserveNow: 'Reservar ahora',
            processing: 'Procesando...',
            perNight: '/noche',
            required: '*',
        },
    };

    const t = translations[currentLang] || translations.en;
    
    const { data, setData, post, processing, errors, reset } = useForm({
        full_name: '',
        email: '',
        phone: '',
        check_in: '',
        check_out: '',
        event_start: '',
        event_end: '',
        number_of_people: 1,
        number_of_adults: 1,
        number_of_children: 0,
        special_request: '',
        accommodation_id: '',
        bookable_type: 'accommodation',
        bookable_id: '',
        room_id: '',
        number_of_rooms: 1,
        price: 0,
        price_usd: 0,
        price_bif: 0,
        turnstile_token: '',
    });

    // State for available rooms and pricing rules
    const [availableRooms, setAvailableRooms] = useState([]);
    const [pricingRule, setPricingRule] = useState(null);
    const [loadingRooms, setLoadingRooms] = useState(false);
    const [eventStartTime, setEventStartTime] = useState('09:00');
    const [eventEndTime, setEventEndTime] = useState('17:00');

    // Sync language from localStorage
    useEffect(() => {
        const savedLang = localStorage.getItem('preferredLanguage') || 'en';
        setCurrentLang(savedLang);

        const handleLanguageChange = (e) => {
            const newLang = e.detail?.language || localStorage.getItem('preferredLanguage') || 'en';
            setCurrentLang(newLang);
        };

        // Listen for custom event (same window) and storage event (other windows)
        window.addEventListener('languageChanged', handleLanguageChange);
        window.addEventListener('storage', handleLanguageChange);
        
        return () => {
            window.removeEventListener('languageChanged', handleLanguageChange);
            window.removeEventListener('storage', handleLanguageChange);
        };
    }, []);

    // Pre-select room or event from URL param on mount
    useEffect(() => {
        const urlParams = new URLSearchParams(window.location.search);
        const roomId = urlParams.get('room');
        const eventId = urlParams.get('event');
        
        if (roomId) {
            isInitializingFromUrl.current = true;
            initialBookableIdFromUrl.current = roomId;
            setBookingType('accommodation');
            setData(prev => ({ ...prev, bookable_id: roomId, accommodation_id: roomId, bookable_type: 'accommodation' }));
        } else if (eventId) {
            isInitializingFromUrl.current = true;
            initialBookableIdFromUrl.current = eventId;
            setBookingType('event_room');
            setData(prev => ({ ...prev, bookable_id: eventId, bookable_type: 'event_room' }));
        }
    }, []);

    // Handle flash messages
    useEffect(() => {
        if (flash?.booking_success) {
            toast.success(flash.booking_success.message || 'Booking placed successfully!');
            reset();
            setNumberOfAdults(1);
            setNumberOfChildren(0);
            setNumberOfRooms(1);
        }
        if (flash?.error) {
            toast.error(flash.error.message || 'An error occurred');
        }
    }, [flash, reset]);

    // Fetch available rooms when accommodation category and dates are selected
    useEffect(() => {
        if (bookingType === 'accommodation' && data.bookable_id && data.check_in && data.check_out) {
            setLoadingRooms(true);
            const accommodationId = data.bookable_id;
            const checkIn = data.check_in;
            const checkOut = data.check_out;

            fetch(`/api/accommodations/${accommodationId}/available-rooms?check_in=${checkIn}&check_out=${checkOut}`)
                .then(response => response.json())
                .then(result => {
                    setAvailableRooms(result.rooms || []);
                    // Use API pricing rule if available (it's the most up-to-date)
                    setPricingRule(result.pricing_rule || null);
                    setLoadingRooms(false);
                    
                    // Reset room selection if selected room is not in available rooms
                    if (data.room_id && !result.rooms.some(r => r.id === parseInt(data.room_id))) {
                        setData('room_id', '');
                    }
                })
                .catch(error => {
                    console.error('Error fetching available rooms:', error);
                    setAvailableRooms([]);
                    // Don't clear pricingRule on error - keep using prop pricing rule
                    setLoadingRooms(false);
                });
        } else {
            setAvailableRooms([]);
            // Only clear pricingRule state when accommodation changes, not when dates are cleared
            // This allows fallback to accommodation prop pricing_rule when dates are not selected
            if (!data.bookable_id) {
                setPricingRule(null);
            }
            setData('room_id', ''); // Clear room selection when accommodation or dates change
        }
    }, [data.bookable_id, data.check_in, data.check_out, bookingType, setData]);

    // Calculate price: accommodation = guests + nights; event/conference = number of rooms booked (not guests)
    useEffect(() => {
        const hasAccommodationSelection = data.bookable_type === 'accommodation' && data.bookable_id && numberOfAdults > 0;
        const hasEventRoomSelection = data.bookable_type === 'event_room' && data.bookable_id;
        if (hasAccommodationSelection || hasEventRoomSelection) {
            let priceBif = 0;
            let priceUsd = 0;
            let priceEur = 0;
            
            if (data.bookable_type === 'accommodation') {
                const selectedAccommodation = accommodations.find(acc => acc.id === parseInt(data.bookable_id));
                
                // Get pricing rule from accommodation prop or from state (fetched via API)
                const accommodationPricingRule = selectedAccommodation?.pricing_rule || null;
                const activePricingRule = pricingRule || accommodationPricingRule;
                
                if (activePricingRule) {
                    // Calculate price per night using pricing rules
                    const basePriceBif = parseFloat(activePricingRule.base_price_bif || 0);
                    const basePriceUsd = parseFloat(activePricingRule.base_price_usd || 0);
                    const basePriceEur = parseFloat(activePricingRule.base_price_eur || 0);
                    
                    const additionalAdults = Math.max(0, numberOfAdults - 1);
                    const additionalAdultBif = parseFloat(activePricingRule.additional_adult_bif || 0) * additionalAdults;
                    const additionalAdultUsd = parseFloat(activePricingRule.additional_adult_usd || 0) * additionalAdults;
                    const additionalAdultEur = parseFloat(activePricingRule.additional_adult_eur || 0) * additionalAdults;
                    
                    const childrenBif = parseFloat(activePricingRule.child_surcharge_bif || 0) * numberOfChildren;
                    const childrenUsd = parseFloat(activePricingRule.child_surcharge_usd || 0) * numberOfChildren;
                    const childrenEur = parseFloat(activePricingRule.child_surcharge_eur || 0) * numberOfChildren;
                    
                    const pricePerNightBif = basePriceBif + additionalAdultBif + childrenBif;
                    const pricePerNightUsd = basePriceUsd + additionalAdultUsd + childrenUsd;
                    const pricePerNightEur = basePriceEur + additionalAdultEur + childrenEur;
                    
                    // If dates are selected, multiply by nights; otherwise show per-night price
                    if (data.check_in && data.check_out) {
                        const checkIn = new Date(data.check_in);
                        const checkOut = new Date(data.check_out);
                        const nights = Math.ceil((checkOut - checkIn) / (1000 * 60 * 60 * 24));
                        priceBif = pricePerNightBif * nights;
                        priceUsd = pricePerNightUsd * nights;
                        priceEur = pricePerNightEur * nights;
                    } else {
                        // Show per-night price when dates not selected yet
                        priceBif = pricePerNightBif;
                        priceUsd = pricePerNightUsd;
                        priceEur = pricePerNightEur;
                    }
                    
                    // Format prices in triple currency format (BIF | USD | EUR)
                    const formattedPrices = formatPriceTripleObject(priceBif, priceUsd, priceEur);
                    setCalculatedPrice(formattedPrices);
                    
                    // Use USD for the main price field (for backend compatibility)
                    setData('price', priceUsd);
                    setData('price_usd', priceUsd);
                    setData('price_bif', priceBif);
                } else if (selectedAccommodation) {
                    // Fallback to base price if pricing rule not available
                    let basePriceBif = parseFloat(selectedAccommodation.price_fbu || 0);
                    let basePriceUsd = parseFloat(selectedAccommodation.price_usd || 0);
                    let basePriceEur = parseFloat(selectedAccommodation.price_eur || 0);
                    
                    if (data.check_in && data.check_out) {
                        const checkIn = new Date(data.check_in);
                        const checkOut = new Date(data.check_out);
                        const nights = Math.ceil((checkOut - checkIn) / (1000 * 60 * 60 * 24));
                        basePriceBif *= nights;
                        basePriceUsd *= nights;
                        basePriceEur *= nights;
                    }
                    
                    const formattedPrices = formatPriceTripleObject(basePriceBif, basePriceUsd, basePriceEur);
                    setCalculatedPrice(formattedPrices);
                    setData('price', basePriceUsd);
                    setData('price_usd', basePriceUsd);
                    setData('price_bif', basePriceBif);
                }
            } else if (data.bookable_type === 'event_room') {
                const selectedEventRoom = eventRooms.find(room => room.id === parseInt(data.bookable_id));
                if (selectedEventRoom) {
                    const rooms = Math.max(1, numberOfRooms);
                    const unitBif = parseFloat(selectedEventRoom.price_fbu || 0);
                    const unitUsd = parseFloat(selectedEventRoom.price_usd || 0);
                    const unitEur = parseFloat(selectedEventRoom.price_eur || 0);
                    priceBif = unitBif * rooms;
                    priceUsd = unitUsd * rooms;
                    priceEur = unitEur * rooms;
                    
                    const formattedPrices = formatPriceTripleObject(priceBif, priceUsd, priceEur);
                    setCalculatedPrice(formattedPrices);
                    setData('price', priceUsd);
                    setData('price_usd', priceUsd);
                    setData('price_bif', priceBif);
                }
            }
        } else {
            setCalculatedPrice({ bifPrice: 0, usdPrice: 0, eurPrice: 0, combined: '0 BIF | 0 USD | 0 EUR' });
            setData('price', 0);
            setData('price_usd', 0);
            setData('price_bif', 0);
        }
    }, [data.bookable_id, data.bookable_type, numberOfAdults, numberOfChildren, numberOfRooms, data.check_in, data.check_out, data.room_id, pricingRule, accommodations, eventRooms, setData]);

    // Update number_of_people, number_of_adults, number_of_children in form data (accommodation)
    useEffect(() => {
        const totalPeople = numberOfAdults + numberOfChildren;
        setData('number_of_people', totalPeople);
        setData('number_of_adults', numberOfAdults);
        setData('number_of_children', numberOfChildren);
    }, [numberOfAdults, numberOfChildren, setData]);

    // Update number_of_rooms in form data (event/conference rooms only)
    useEffect(() => {
        setData('number_of_rooms', Math.max(1, numberOfRooms));
    }, [numberOfRooms, setData]);

    // Load Turnstile widget
    useEffect(() => {
        // Set up global callback first
        window.turnstileCallback = (token) => {
            setData('turnstile_token', token);
        };

        const initTurnstile = () => {
            if (window.turnstile && turnstileSiteKey) {
                setTurnstileReady(true);
                // Wait for DOM to be ready, then render manually
                setTimeout(() => {
                    const container = document.getElementById('turnstile-container');
                    if (container && !container.hasChildNodes()) {
                        window.turnstile.render(container, {
                            sitekey: turnstileSiteKey,
                            callback: window.turnstileCallback,
                            theme: 'light',
                        });
                    }
                }, 100);
            }
        };

        // Check if script already exists
        const existingScript = document.querySelector('script[src="https://challenges.cloudflare.com/turnstile/v0/api.js"]');
        
        if (existingScript) {
            // Script exists, wait for it to be ready
            if (window.turnstile) {
                initTurnstile();
            } else {
                const checkInterval = setInterval(() => {
                    if (window.turnstile) {
                        clearInterval(checkInterval);
                        initTurnstile();
                    }
                }, 100);
                setTimeout(() => clearInterval(checkInterval), 5000);
            }
        } else {
            const script = document.createElement('script');
            script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js';
            script.async = true;
            script.defer = true;
            script.onload = () => {
                initTurnstile();
            };
            document.body.appendChild(script);
        }

        return () => {
            // Cleanup: remove the widget if it exists
            if (window.turnstile) {
                const container = document.getElementById('turnstile-container');
                if (container) {
                    try {
                        window.turnstile.remove(container);
                    } catch (e) {
                        // Widget might not exist
                    }
                }
            }
            delete window.turnstileCallback;
        };
    }, [setData, turnstileSiteKey]);

    useEffect(() => {
        const checkScripts = () => {
            if (window.$ && window.$.fn.datepicker) {
                setScriptsReady(true);
                return true;
            }
            return false;
        };

        if (checkScripts()) return;

        const intervalId = setInterval(() => {
            if (checkScripts()) {
                clearInterval(intervalId);
            }
        }, 50);

        return () => clearInterval(intervalId);
    }, []);

    const formatDateForBackend = useCallback((date) => {
        if (!date) return '';
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }, []);

    const formatDateTimeForBackend = useCallback((date, timeString = '00:00') => {
        if (!date) return '';
        const [hours = '00', minutes = '00'] = timeString.split(':');
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day} ${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:00`;
    }, []);

    useLayoutEffect(() => {
        if (!scriptsReady) return;

        const DATEPICKER_FORMAT = 'd MM, yyyy';
        const $ = window.$;
        
        // Get current date for startDate constraint
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        const getEventStartTime = () => {
            const timeInput = document.getElementById('event_start_time');
            return timeInput?.value || '09:00';
        };
        const getEventEndTime = () => {
            const timeInput = document.getElementById('event_end_time');
            return timeInput?.value || '17:00';
        };

        // Store update functions globally for time input handlers
        window.updateEventStartDateTime = (date) => {
            setData('event_start', formatDateTimeForBackend(date, getEventStartTime()));
        };
        window.updateEventEndDateTime = (date) => {
            setData('event_end', formatDateTimeForBackend(date, getEventEndTime()));
        };

        const destroyDatePickers = () => {
            ['#checkin_date', '#checkout_date', '#event_start_date', '#event_end_date'].forEach(selector => {
                const $el = $(selector);
                if ($el.length && $el.data('datepicker')) {
                    $el.datepicker('destroy');
                }
            });
        };

        destroyDatePickers();
        datePickersInitialized.current = false;

        if (bookingType === 'accommodation') {
            const $checkin = $('#checkin_date');
            const $checkout = $('#checkout_date');

            if ($checkin.length && $checkout.length) {
                $checkin.datepicker({
                    format: DATEPICKER_FORMAT,
                    autoclose: true,
                    startDate: today,
                    todayHighlight: true,
                }).on('changeDate', (e) => {
                    if (e.date) setData('check_in', formatDateForBackend(e.date));
                });

                $checkout.datepicker({
                    format: DATEPICKER_FORMAT,
                    autoclose: true,
                    startDate: today,
                    todayHighlight: true,
                }).on('changeDate', (e) => {
                    if (e.date) setData('check_out', formatDateForBackend(e.date));
                });

                datePickersInitialized.current = true;
            }
        } else {
            const $eventStart = $('#event_start_date');
            const $eventEnd = $('#event_end_date');

            if ($eventStart.length && $eventEnd.length) {
                $eventStart.datepicker({
                    format: DATEPICKER_FORMAT,
                    autoclose: true,
                    startDate: today,
                    todayHighlight: true,
                }).on('changeDate', (e) => {
                    if (e.date) window.updateEventStartDateTime(e.date);
                });

                $eventEnd.datepicker({
                    format: DATEPICKER_FORMAT,
                    autoclose: true,
                    startDate: today,
                    todayHighlight: true,
                }).on('changeDate', (e) => {
                    if (e.date) window.updateEventEndDateTime(e.date);
                });

                datePickersInitialized.current = true;
            }
        }

        return () => {
            destroyDatePickers();
            delete window.updateEventStartDateTime;
            delete window.updateEventEndDateTime;
        };
    }, [scriptsReady, bookingType, setData, formatDateForBackend, formatDateTimeForBackend]);

    // Handle booking type change
    useEffect(() => {
        setData('bookable_type', bookingType);
        
        const shouldPreserveBookableId = initialBookableIdFromUrl.current !== null &&
                                         data.bookable_id === initialBookableIdFromUrl.current;

        if (!isInitializingFromUrl.current && !shouldPreserveBookableId) {
            setData('bookable_id', '');
            setData('accommodation_id', '');
            setData('check_in', '');
            setData('check_out', '');
            setData('event_start', '');
            setData('event_end', '');
            setData('number_of_rooms', 1);
            setNumberOfRooms(1);
            setCalculatedPrice({ bifPrice: 0, usdPrice: 0, eurPrice: 0, combined: '0 BIF | 0 USD | 0 EUR' });
            setData('price', 0);
            
            setEventStartTime('09:00');
            setEventEndTime('17:00');
        } else if (isInitializingFromUrl.current) {
            // Reset the flag after initialization, but keep the initial bookable_id ref
            isInitializingFromUrl.current = false;
        }
    }, [bookingType]);

    // Restore bookable_id from URL params if it was cleared during bookingType change
    useEffect(() => {
        if (initialBookableIdFromUrl.current !== null && !data.bookable_id) {
            const isEventRoom = eventRooms.some(r => String(r.id) === initialBookableIdFromUrl.current);
            const isAccommodation = accommodations.some(a => String(a.id) === initialBookableIdFromUrl.current);
            
            if ((isEventRoom && bookingType === 'event_room') || (isAccommodation && bookingType === 'accommodation')) {
                setData('bookable_id', initialBookableIdFromUrl.current);
                if (bookingType === 'accommodation') {
                    setData('accommodation_id', initialBookableIdFromUrl.current);
                }
            }
        }
    }, [bookingType, data.bookable_id, setData, eventRooms, accommodations]);

    const handleBookableChange = (e) => {
        const selected = e.target.selectedOptions?.[0];
        const bookableId = selected?.dataset?.value || e.target.value;
        setData('bookable_id', bookableId);
        setData('room_id', '');
        if (bookingType === 'accommodation') {
            setData('accommodation_id', bookableId);
        }
    };

    const handleBookingTypeChange = (e) => {
        const selected = e.target.selectedOptions?.[0];
        const raw = (selected?.dataset?.value || e.target.value || '').toString().toLowerCase();

        // Prefer canonical data-value if present
        let nextType = selected?.dataset?.value;

        if (!nextType) {
            if (raw.includes('event') || raw.includes('réception') || raw.includes('reception') || raw.includes('salle')) {
                nextType = 'event_room';
            } else {
                nextType = 'accommodation';
            }
        }

        setBookingType(nextType);
    };

    const handleAdultsChange = (e) => {
        const adults = parseInt(e.target.value) || 1;
        setNumberOfAdults(adults);
    };

    const handleChildrenChange = (e) => {
        const children = parseInt(e.target.value) || 0;
        setNumberOfChildren(children);
    };

    const handleNumberOfRoomsChange = (e) => {
        const rooms = parseInt(e.target.value) || 1;
        setNumberOfRooms(Math.max(1, rooms));
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        
        if (!data.turnstile_token) {
            toast.error('Please complete the CAPTCHA verification');
            return;
        }

        if (!data.email && !data.phone) {
            toast.error('Please provide either email or phone number');
            return;
        }

        if (!data.bookable_id) {
            toast.error(`Please select an ${bookingType === 'accommodation' ? 'accommodation' : 'event room'}`);
            return;
        }

        if (bookingType === 'accommodation') {
            if (!data.check_in || !data.check_out) {
                toast.error('Please select check-in and check-out dates');
                return;
            }
        } else {
            if (!data.event_start || !data.event_end) {
                toast.error('Please select event start and end date/time');
                return;
            }
        }

        const payload = {
            ...data,
            bookable_type: bookingType, // enforce canonical value
            bookable_id: data.bookable_id,
            accommodation_id: bookingType === 'accommodation' ? data.accommodation_id : null,
            room_id: bookingType === 'accommodation' ? data.room_id : null,
        };

        post('/api/booking', payload, {
            preserveScroll: true,
            onSuccess: () => {
                // Success handled by flash message
            },
            onError: (errors) => {
                console.error('Booking submission failed', { errors, payload });
                if (errors.turnstile) {
                    toast.error('CAPTCHA verification failed. Please try again.');
                } else if (errors.contact) {
                    toast.error('Please provide either email or phone number');
                } else if (errors.dates) {
                    toast.error('Check-in and check-out dates are required');
                } else if (errors.event_dates) {
                    toast.error('Event start and end dates are required');
                } else if (errors.bookable_id) {
                    toast.error('Please reselect the event room.');
                } else if (errors.bookable_type) {
                    toast.error('Please reselect booking type.');
                } else {
                    toast.error('Failed to submit booking. Please check all fields.');
                }
            }
        });
    };

    // Extract company information with fallbacks
    const address = siteinfo?.address || '';
    const phone = siteinfo?.phone || '';
    const email = siteinfo?.email || '';

    return (
        <>
            <Toaster />
            <section className="section contact-section" id="next">
                <div className="container">
                    <div className="row">
                        <div className="col-md-7" data-aos="fade-up" data-aos-delay="100">
                            <form onSubmit={handleSubmit} className="bg-white p-md-5 p-4 mb-5 border notranslate" translate="no">
                                <div className="row">
                                    <div className="col-md-6 form-group">
                                        <label className="text-black font-weight-bold" htmlFor="full_name">{t.name} <span className="text-danger">{t.required}</span></label>
                                        <input 
                                            type="text" 
                                            id="full_name" 
                                            className={`form-control ${errors.full_name ? 'is-invalid' : ''}`}
                                            value={data.full_name}
                                            onChange={(e) => setData('full_name', e.target.value)}
                                            required
                                        />
                                        {errors.full_name && <div className="invalid-feedback">{errors.full_name}</div>}
                                    </div>
                                    <div className="col-md-6 form-group">
                                        <label className="text-black font-weight-bold" htmlFor="phone">{t.phone}</label>
                                        <input 
                                            type="text" 
                                            id="phone" 
                                            className={`form-control ${errors.phone ? 'is-invalid' : ''}`}
                                            value={data.phone}
                                            onChange={(e) => setData('phone', e.target.value)}
                                        />
                                        {errors.phone && <div className="invalid-feedback">{errors.phone}</div>}
                                    </div>
                                </div>

                                <div className="row">
                                    <div className="col-md-12 form-group">
                                        <label className="text-black font-weight-bold" htmlFor="email">{t.email}</label>
                                        <input 
                                            type="email" 
                                            id="email" 
                                            className={`form-control ${errors.email ? 'is-invalid' : ''}`}
                                            value={data.email}
                                            onChange={(e) => setData('email', e.target.value)}
                                        />
                                        {errors.email && <div className="invalid-feedback">{errors.email}</div>}
                                    </div>
                                </div>

                                <div className="row">
                                    <div className="col-md-12 form-group">
                                        <label className="text-black font-weight-bold" htmlFor="booking_type">{t.bookingType} <span className="text-danger">{t.required}</span></label>
                                        <select 
                                            id="booking_type"
                                            className="form-control notranslate"
                                            translate="no"
                                            value={bookingType}
                                            onChange={handleBookingTypeChange}
                                            required
                                        >
                                            <option className="notranslate" translate="no" value="accommodation" data-value="accommodation">{t.accommodation}</option>
                                            <option className="notranslate" translate="no" value="event_room" data-value="event_room">{t.eventRoom}</option>
                                        </select>
                                    </div>
                                </div>

                                <div className="row">
                                    <div className="col-md-12 form-group">
                                        <label className="text-black font-weight-bold" htmlFor="bookable">
                                            {bookingType === 'accommodation' ? t.accommodation : t.eventRoom} <span className="text-danger">{t.required}</span>
                                        </label>
                                        <select 
                                            id="bookable"
                                            className={`form-control ${errors.bookable_id ? 'is-invalid' : ''}`}
                                            value={data.bookable_id}
                                            onChange={handleBookableChange}
                                            required
                                        >
                                            <option value="">{bookingType === 'accommodation' ? t.selectAccommodation : t.selectEventRoom}</option>
                                            {bookingType === 'accommodation' 
                                                ? accommodations.map((acc) => {
                                                    // Display category name if available, otherwise room_name
                                                    const displayName = acc.room_category || acc.room_name;
                                                    const priceDisplay = formatPriceTriple(acc.price_fbu, acc.price_usd, acc.price_eur);
                                                    return (
                                                        <option key={acc.id} value={acc.id} data-value={acc.id}>
                                                            {displayName} - {priceDisplay}{t.perNight}
                                                        </option>
                                                    );
                                                })
                                                : eventRooms.map((room) => {
                                                    const priceDisplay = formatPriceTriple(room.price_fbu, room.price_usd, room.price_eur);
                                                    return (
                                                        <option key={room.id} value={room.id} data-value={room.id}>
                                                            {room.name} - {priceDisplay}
                                                        </option>
                                                    );
                                                })
                                            }
                                        </select>
                                        {errors.bookable_id && <div className="invalid-feedback">{errors.bookable_id}</div>}
                                    </div>
                                </div>

                                {bookingType === 'accommodation' ? (
                                    <>
                                        <div className="row">
                                            <div className="col-md-6 form-group">
                                                <label className="text-black font-weight-bold" htmlFor="checkin_date">{t.checkIn} <span className="text-danger">{t.required}</span></label>
                                                <div className="field-icon-wrap">
                                                    <div className="icon"><span className="icon-calendar"></span></div>
                                                    <input 
                                                        type="text" 
                                                        id="checkin_date" 
                                                        className={`form-control ${errors.check_in ? 'is-invalid' : ''}`}
                                                        readOnly
                                                        onFocus={() => {
                                                            if (window.$ && window.$.fn.datepicker) {
                                                                window.$('#checkin_date').datepicker('show');
                                                            }
                                                        }}
                                                        required
                                                    />
                                                </div>
                                                {errors.check_in && <div className="invalid-feedback">{errors.check_in}</div>}
                                            </div>
                                            <div className="col-md-6 form-group">
                                                <label className="text-black font-weight-bold" htmlFor="checkout_date">{t.checkOut} <span className="text-danger">{t.required}</span></label>
                                                <div className="field-icon-wrap">
                                                    <div className="icon"><span className="icon-calendar"></span></div>
                                                    <input 
                                                        type="text" 
                                                        id="checkout_date" 
                                                        className={`form-control ${errors.check_out ? 'is-invalid' : ''}`}
                                                        readOnly
                                                        onFocus={() => {
                                                            if (window.$ && window.$.fn.datepicker) {
                                                                window.$('#checkout_date').datepicker('show');
                                                            }
                                                        }}
                                                        required
                                                    />
                                                </div>
                                                {errors.check_out && <div className="invalid-feedback">{errors.check_out}</div>}
                                            </div>
                                        </div>

                                        {/* Room Selection */}
                                        {data.bookable_id && data.check_in && data.check_out && (
                                            <div className="row">
                                                <div className="col-md-12 form-group">
                                                    <label className="text-black font-weight-bold" htmlFor="room_id">
                                                        {t.selectRoomNumber} <span className="text-danger">{t.required}</span>
                                                    </label>
                                                    {loadingRooms ? (
                                                        <div className="text-muted">{t.loadingRooms}</div>
                                                    ) : availableRooms.length > 0 ? (
                                                        <select
                                                            id="room_id"
                                                            className={`form-control ${errors.room_id ? 'is-invalid' : ''}`}
                                                            value={data.room_id}
                                                            onChange={(e) => setData('room_id', e.target.value)}
                                                            required
                                                        >
                                                            <option value="">{t.selectRoom}</option>
                                                            {availableRooms.map((room) => (
                                                                <option key={room.id} value={room.id}>
                                                                    {room.display_name || `Room ${room.room_number}`}
                                                                </option>
                                                            ))}
                                                        </select>
                                                    ) : (
                                                        <div className="alert alert-warning">
                                                            {t.noRoomsAvailable}
                                                        </div>
                                                    )}
                                                    {errors.room_id && <div className="invalid-feedback">{errors.room_id}</div>}
                                                </div>
                                            </div>
                                        )}
                                    </>
                                ) : (
                                    <div className="row">
                                        <div className="col-md-6 form-group">
                                            <label className="text-black font-weight-bold" htmlFor="event_start_date">{t.eventStartDate} <span className="text-danger">{t.required}</span></label>
                                            <div className="field-icon-wrap">
                                                <div className="icon"><span className="icon-calendar"></span></div>
                                                <input 
                                                    type="text" 
                                                    id="event_start_date" 
                                                    className={`form-control ${errors.event_start ? 'is-invalid' : ''}`}
                                                    readOnly
                                                    onFocus={() => {
                                                        if (window.$ && window.$.fn.datepicker) {
                                                            window.$('#event_start_date').datepicker('show');
                                                        }
                                                    }}
                                                    required
                                                />
                                            </div>
                                            <label className="text-black font-weight-bold mt-2" htmlFor="event_start_time">{t.eventStartTime} <span className="text-danger">{t.required}</span></label>
                                            <input 
                                                type="time" 
                                                id="event_start_time" 
                                                className="form-control"
                                                value={eventStartTime}
                                                onChange={(e) => {
                                                    const newTime = e.target.value || '00:00';
                                                    setEventStartTime(newTime);
                                                    // Update datetime if date is already selected
                                                    const dateInput = document.getElementById('event_start_date');
                                                    if (dateInput && dateInput.value && window.$ && window.updateEventStartDateTime) {
                                                        const $dateInput = window.$(dateInput);
                                                        const datepickerData = $dateInput.data('datepicker');
                                                        if (datepickerData && datepickerData.date) {
                                                            window.updateEventStartDateTime(datepickerData.date);
                                                        }
                                                    }
                                                }}
                                                required
                                            />
                                            {errors.event_start && <div className="invalid-feedback d-block">{errors.event_start}</div>}
                                        </div>
                                        <div className="col-md-6 form-group">
                                            <label className="text-black font-weight-bold" htmlFor="event_end_date">{t.eventEndDate} <span className="text-danger">{t.required}</span></label>
                                            <div className="field-icon-wrap">
                                                <div className="icon"><span className="icon-calendar"></span></div>
                                                <input 
                                                    type="text" 
                                                    id="event_end_date" 
                                                    className={`form-control ${errors.event_end ? 'is-invalid' : ''}`}
                                                    readOnly
                                                    onFocus={() => {
                                                        if (window.$ && window.$.fn.datepicker) {
                                                            window.$('#event_end_date').datepicker('show');
                                                        }
                                                    }}
                                                    required
                                                />
                                            </div>
                                            <label className="text-black font-weight-bold mt-2" htmlFor="event_end_time">{t.eventEndTime} <span className="text-danger">{t.required}</span></label>
                                            <input 
                                                type="time" 
                                                id="event_end_time" 
                                                className="form-control"
                                                value={eventEndTime}
                                                onChange={(e) => {
                                                    const newTime = e.target.value || '00:00';
                                                    setEventEndTime(newTime);
                                                    const dateInput = document.getElementById('event_end_date');
                                                    if (dateInput && dateInput.value && window.$ && window.updateEventEndDateTime) {
                                                        const $dateInput = window.$(dateInput);
                                                        const datepickerData = $dateInput.data('datepicker');
                                                        if (datepickerData && datepickerData.date) {
                                                            window.updateEventEndDateTime(datepickerData.date);
                                                        }
                                                    }
                                                }}
                                                required
                                            />
                                            {errors.event_end && <div className="invalid-feedback d-block">{errors.event_end}</div>}
                                        </div>
                                    </div>
                                )}

                                {bookingType === 'event_room' && (
                                    <div className="row">
                                        <div className="col-md-6 form-group">
                                            <label htmlFor="number_of_rooms" className="font-weight-bold text-black">{t.numberOfRooms} <span className="text-danger">{t.required}</span></label>
                                            <div className="field-icon-wrap">
                                                <div className="icon"><span className="ion-ios-arrow-down"></span></div>
                                                <select
                                                    name="number_of_rooms"
                                                    id="number_of_rooms"
                                                    className="form-control"
                                                    value={numberOfRooms}
                                                    onChange={handleNumberOfRoomsChange}
                                                >
                                                    <option value="1">1</option>
                                                    <option value="2">2</option>
                                                    <option value="3">3</option>
                                                    <option value="4">4</option>
                                                    <option value="5">5</option>
                                                    <option value="6">6</option>
                                                    <option value="7">7</option>
                                                    <option value="8">8</option>
                                                    <option value="9">9</option>
                                                    <option value="10">10+</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {bookingType === 'accommodation' && (
                                    <div className="row">
                                        <div className="col-md-6 form-group">
                                            <label htmlFor="adults" className="font-weight-bold text-black">{t.adults}</label>
                                            <div className="field-icon-wrap">
                                                <div className="icon"><span className="ion-ios-arrow-down"></span></div>
                                                <select 
                                                    name="adults" 
                                                    id="adults" 
                                                    className="form-control"
                                                    value={numberOfAdults}
                                                    onChange={handleAdultsChange}
                                                >
                                                    <option value="1">1</option>
                                                    <option value="2">2</option>
                                                    <option value="3">3</option>
                                                    <option value="4">4</option>
                                                    <option value="5">5</option>
                                                    <option value="6">6</option>
                                                    <option value="7">7</option>
                                                    <option value="8">8+</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div className="col-md-6 form-group">
                                            <label htmlFor="children" className="font-weight-bold text-black">{t.children}</label>
                                            <div className="field-icon-wrap">
                                                <div className="icon"><span className="ion-ios-arrow-down"></span></div>
                                                <select 
                                                    name="children" 
                                                    id="children" 
                                                    className="form-control"
                                                    value={numberOfChildren}
                                                    onChange={handleChildrenChange}
                                                >
                                                    <option value="0">0</option>
                                                    <option value="1">1</option>
                                                    <option value="2">2</option>
                                                    <option value="3">3</option>
                                                    <option value="4">4</option>
                                                    <option value="5">5</option>
                                                    <option value="6">6+</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {calculatedPrice.combined && calculatedPrice.combined !== '0 BIF | 0 USD | 0 EUR' && (
                                    <div className="row mb-3">
                                        <div className="col-md-12">
                                            <div className="alert alert-info">
                                                <strong style={{ fontSize: '1.1rem', color: '#c9a227' }}>
                                                    {t.estimatedPrice}: {calculatedPrice.combined}
                                                </strong>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                <div className="row mb-4">
                                    <div className="col-md-12 form-group">
                                        <label className="text-black font-weight-bold" htmlFor="special_request">{t.notes}</label>
                                        <textarea 
                                            name="special_request" 
                                            id="special_request" 
                                            className={`form-control ${errors.special_request ? 'is-invalid' : ''}`}
                                            cols="30" 
                                            rows="8"
                                            value={data.special_request}
                                            onChange={(e) => setData('special_request', e.target.value)}
                                        ></textarea>
                                        {errors.special_request && <div className="invalid-feedback">{errors.special_request}</div>}
                                    </div>
                                </div>

                                {/* Turnstile CAPTCHA */}
                                <div className="row mb-3">
                                    <div className="col-md-12 notranslate" translate="no">
                                        {turnstileSiteKey && (
                                            <div id="turnstile-container" className="notranslate" translate="no"></div>
                                        )}
                                        {!turnstileReady && turnstileSiteKey && (
                                            <div className="text-muted small">{t.loadingCaptcha}</div>
                                        )}
                                        {errors.turnstile && <div className="text-danger small mt-1">{errors.turnstile}</div>}
                                    </div>
                                </div>

                                <div className="row">
                                    <div className="col-md-6 form-group">
                                        <button 
                                            type="submit" 
                                            className="btn btn-primary text-white py-3 px-5 font-weight-bold"
                                            disabled={processing}
                                        >
                                            {processing ? t.processing : t.reserveNow}
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div className="col-md-5" data-aos="fade-up" data-aos-delay="200">
                            <div className="row">
                                <div className="col-md-10 ml-auto contact-info">
                                    {address && (
                                        <p><span className="d-block">Address:</span> <span className="text-black">{address}</span></p>
                                    )}
                                    {phone && (
                                        <p><span className="d-block">Phone:</span> <span className="text-black">{phone}</span></p>
                                    )}
                                    {email && (
                                        <p><span className="d-block">Email:</span> <span className="text-black">{email}</span></p>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </>
    );
}
