import { createSignal, createUniqueId } from 'solid-js';
import type { HeroContent } from '../home/hero/HeroContent';
import type { Car } from '../home/slider/SliderContent';

export const sanitizeInput = (str: string) => str.replace(/[<>]/g, '').trim();

type FormType = 'main' | 'slider' | 'action';

interface UseBookingFormProps {
    content: HeroContent;
    // car убираем из обязательных пропсов инициализации, будем задавать его реактивно
    car?: Car;
    showDiscount?: boolean;
    formType?: FormType;
}

export function createBookingForm(props: UseBookingFormProps) {
    // 1. Создаем сигнал для машины, инициализируем тем, что пришло сразу (или undefined)
    const [selectedCar, setSelectedCar] = createSignal<Car | undefined>(props.car);

    const [pickup, setPickup] = createSignal('');
    const [pickupDate, setPickupDate] = createSignal('');
    const [pickupTime, setPickupTime] = createSignal('');
    const [dropoff, setDropoff] = createSignal('');
    const [dropoffDate, setDropoffDate] = createSignal('');
    const [dropoffTime, setDropoffTime] = createSignal('');
    const [passengers, setPassengers] = createSignal('');
    const [phone, setPhone] = createSignal('');
    const [name, setName] = createSignal('');
    const [additionalInfo, setAdditionalInfo] = createSignal('');
    const [applyDiscount, setApplyDiscount] = createSignal(props.showDiscount || false);
    const [honeypot, setHoneypot] = createSignal('');
    const [errors, setErrors] = createSignal<Record<string, string>>({});
    const [loading, setLoading] = createSignal(false);
    const [successMessage, setSuccessMessage] = createSignal<string | null>(null);
    const [errorMessage, setErrorMessage] = createSignal<string | null>(null);

    const ids = {
        pickup: createUniqueId(),
        pickupDate: createUniqueId(),
        pickupTime: createUniqueId(),
        dropoff: createUniqueId(),
        dropoffDate: createUniqueId(),
        dropoffTime: createUniqueId(),
        passengers: createUniqueId(),
        name: createUniqueId(),
        phone: createUniqueId(),
        additionalInfo: createUniqueId(),
        applyDiscount: createUniqueId(),
    };

    const resetForm = () => {
        setPickup(''); setPickupDate(''); setPickupTime('');
        setDropoff(''); setDropoffDate(''); setDropoffTime('');
        setPassengers(''); setPhone(''); setName(''); setAdditionalInfo('');
        setApplyDiscount(props.showDiscount || false);
        setErrors({});
        // Машину не сбрасываем, так как она выбрана пользователем
    };

    const validate = (): boolean => {
        const newErrors: Record<string, string> = {};
        const now = new Date();
        const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());

        if (!pickup().trim()) newErrors.pickup = props.content.fieldRequired;
        else if (sanitizeInput(pickup()).length < 3) newErrors.pickup = "Adresse ist zu kurz";

        const pDate = pickupDate() ? new Date(pickupDate()) : null;
        if (!pickupDate()) newErrors.pickupDate = props.content.fieldRequired;
        else if (pDate && pDate < todayStart) newErrors.pickupDate = props.content.dateMustBeFuture;

        if (!pickupTime()) newErrors.pickupTime = props.content.fieldRequired;

        if (!dropoff().trim()) newErrors.dropoff = props.content.fieldRequired;
        else if (sanitizeInput(dropoff()).length < 3) newErrors.dropoff = "Adresse ist zu kurz";

        const dDate = dropoffDate() ? new Date(dropoffDate()) : null;
        if (!dropoffDate()) newErrors.dropoffDate = props.content.fieldRequired;

        if (!dropoffTime()) newErrors.dropoffTime = props.content.fieldRequired;

        if (!passengers()) newErrors.passengers = props.content.fieldRequired;
        if (!name().trim()) newErrors.name = props.content.invalidName;

        const phoneDigits = phone().replace(/\D/g, '');
        if (phoneDigits.length < 11) newErrors.phone = props.content.invalidPhone || "Nummer ist zu kurz";

        setErrors(newErrors);

        if (Object.keys(newErrors).length > 0) {
            const firstErrorId = Object.keys(newErrors)[0];
            const elementId = ids[firstErrorId as keyof typeof ids];
            document.getElementById(elementId)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
            document.getElementById(elementId)?.focus();
        }

        return Object.keys(newErrors).length === 0;
    };

    const closeSuccess = () => {
        setSuccessMessage(null);
        if (typeof window !== 'undefined') {
            window.dispatchEvent(new CustomEvent('booking-close-modal'));
        }
    };

    const submitForm = async (e: Event) => {
        e.preventDefault();
        if (honeypot() || !validate()) return;

        setLoading(true);

        // 2. Получаем текущее значение машины из сигнала
        const currentCar = selectedCar();

        try {
            const requestBody = {
                // 3. Используем currentCar вместо props.car
                ...(currentCar && {
                    carDetails: {
                        make: currentCar.make,
                        model: currentCar.model,
                        year: currentCar.year,
                        price: currentCar.price,
                    }
                }),
                discount: (props.showDiscount && applyDiscount()) ? '20% Aktion' : undefined,
                formType: props.formType || 'main',
                pickup: sanitizeInput(pickup()),
                pickupDate: pickupDate(),
                pickupTime: pickupTime(),
                dropoff: sanitizeInput(dropoff()),
                dropoffDate: dropoffDate(),
                dropoffTime: dropoffTime(),
                passengers: passengers(),
                phone: phone(),
                name: sanitizeInput(name()),
                additionalInfo: sanitizeInput(additionalInfo()),
            };

            const response = await fetch('/api/send-booking', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(requestBody),
            });

            if (response.ok) {
                const msg = props.content.bookingSubmitted || "Buchung erfolgreich!";
                setSuccessMessage(msg);
                setErrorMessage(null);

                if (typeof window !== 'undefined') {
                    window.dispatchEvent(new CustomEvent('booking-success', { detail: { message: msg } }));
                }

                resetForm();

                setTimeout(() => {
                    closeSuccess();
                }, 5000);

            } else {
                const errorData = await response.json();
                const errorMsg = errorData.error || props.content.somethingWentWrong;
                setErrorMessage(errorMsg);
                setSuccessMessage(null);

                if (typeof window !== 'undefined') {
                    window.dispatchEvent(new CustomEvent('booking-error', { detail: { message: errorMsg } }));
                }
            }
        } catch (err) {
            console.error(err);
            setErrorMessage(props.content.somethingWentWrong);
        } finally {
            setLoading(false);
        }
    };

    return {
        pickup, setPickup, pickupDate, setPickupDate, pickupTime, setPickupTime,
        dropoff, setDropoff, dropoffDate, setDropoffDate, dropoffTime, setDropoffTime,
        passengers, setPassengers, phone, setPhone, name, setName,
        additionalInfo, setAdditionalInfo, applyDiscount, setApplyDiscount,
        honeypot, setHoneypot,
        errors, loading, ids,
        successMessage, errorMessage,
        submitForm,
        closeSuccess,
        setSelectedCar
    };
}