import { type Component, Show, createEffect } from 'solid-js'; // Добавили createEffect
import { FaSolidCircleExclamation, FaSolidCheck, FaSolidXmark, FaSolidClock } from 'solid-icons/fa';

import type { HeroContent } from '../home/hero/HeroContent';
import type { Car } from '../home/slider/SliderContent';
import { Button } from '@/components/base/Buttons';

import { createBookingForm } from './useBookingForm';
import { BookingCarSummary } from './BookingCarSummary';
import { LocationFieldset } from './LocationFieldset';
import { PersonalDetails } from './PersonalDetails';

import { colorMap } from './styles';

interface UniversalBookingFormProps {
    content: HeroContent;
    car?: Car;
    showDiscount?: boolean;
    formType?: 'main' | 'slider' | 'action';
    accentColor?: 'amber' | 'red' | 'blue';
}

export const UniversalBookingForm: Component<UniversalBookingFormProps> = (props) => {
    if (!props.content) return null;

    const accentColor = () => props.accentColor || 'amber';

    const form = createBookingForm({
        content: props.content,
        car: props.car, // Это начальное значение
        showDiscount: props.showDiscount,
        formType: props.formType,
    });

    // ВАЖНО: Следим за изменением props.car и обновляем хук
    createEffect(() => {
        // Когда props.car меняется (при клике на карточку),
        // обновляем внутреннее состояние хука
        form.setSelectedCar(props.car);
    });

    return (
        <div class="relative w-full h-full min-h-[400px]">

            {/* Блок Успеха */}
            <Show when={form.successMessage()}>
                <div class="absolute inset-0 z-50 flex flex-col items-center justify-center bg-white rounded-xl p-8 animate-fadeIn">

                    <div class={`w-20 h-20 rounded-full bg-green-50 flex items-center justify-center mb-6 shadow-sm border border-green-100`}>
                        <FaSolidCheck class="w-10 h-10 text-green-500" />
                    </div>

                    <h3 class="text-3xl font-bold text-gray-900 mb-3 tracking-tight">
                        Vielen Dank!
                    </h3>
                    <p class="text-gray-600 text-lg text-center leading-relaxed mb-8 max-w-xs mx-auto">
                        {form.successMessage()}
                    </p>

                    <div class="flex items-center gap-2 px-4 py-2 bg-gray-50 rounded-full text-sm font-medium text-gray-400 border border-gray-100">
                        <FaSolidClock class="w-4 h-4" />
                        <span>Schließt automatisch in 5 Sek.</span>
                    </div>
                </div>
            </Show>

            {/* Блок Ошибки */}
            <Show when={form.errorMessage()}>
                <div class="mb-6 p-4 rounded-lg bg-red-50 border border-red-200 animate-fadeIn shadow-sm">
                    <div class="flex items-start">
                        <div class="flex-shrink-0 mt-0.5">
                            <FaSolidCircleExclamation class="h-5 w-5 text-red-500" />
                        </div>
                        <div class="ml-3">
                            <h3 class="text-sm font-semibold text-red-800">
                                Ein Fehler ist aufgetreten
                            </h3>
                            <p class="text-sm text-red-700 mt-1">
                                {form.errorMessage()}
                            </p>
                        </div>
                    </div>
                </div>
            </Show>

            {/* Основная Форма */}
            <Show when={!form.successMessage()}>
                <form onSubmit={form.submitForm} class="space-y-6 text-gray-900" noValidate>

                    <BookingCarSummary car={props.car} />

                    <div class="sr-only" aria-hidden="true">
                        <input
                            type="text"
                            name="confirm_email"
                            tabIndex={-1}
                            autocomplete="off"
                            value={form.honeypot()}
                            onInput={(e) => form.setHoneypot(e.currentTarget.value)}
                        />
                    </div>

                    <LocationFieldset
                        title={props.content.pickupDetailsTitle}
                        accentColor={accentColor()}
                        locationId={form.ids.pickup}
                        dateId={form.ids.pickupDate}
                        timeId={form.ids.pickupTime}
                        locationLabel={props.content.pickup}
                        locationPlaceholder={props.content.pickupPlaceholder}
                        dateLabel={props.content.date}
                        timeLabel={props.content.time}
                        locationValue={form.pickup()}
                        dateValue={form.pickupDate()}
                        timeValue={form.pickupTime()}
                        onLocationChange={form.setPickup}
                        onDateChange={form.setPickupDate}
                        onTimeChange={form.setPickupTime}
                        locationError={form.errors().pickup}
                        dateError={form.errors().pickupDate}
                        timeError={form.errors().pickupTime}
                        minDate={new Date().toISOString().split('T')[0]}
                    />

                    <LocationFieldset
                        title={props.content.dropoffDetailsTitle}
                        accentColor={accentColor()}
                        locationId={form.ids.dropoff}
                        dateId={form.ids.dropoffDate}
                        timeId={form.ids.dropoffTime}
                        locationLabel={props.content.dropoff}
                        locationPlaceholder={props.content.dropoffPlaceholder}
                        dateLabel={props.content.date}
                        timeLabel={props.content.time}
                        locationValue={form.dropoff()}
                        dateValue={form.dropoffDate()}
                        timeValue={form.dropoffTime()}
                        onLocationChange={form.setDropoff}
                        onDateChange={form.setDropoffDate}
                        onTimeChange={form.setDropoffTime}
                        locationError={form.errors().dropoff}
                        dateError={form.errors().dropoffDate}
                        timeError={form.errors().dropoffTime}
                        minDate={form.pickupDate() || new Date().toISOString().split('T')[0]}
                    />

                    <PersonalDetails
                        accentColor={accentColor()}
                        content={props.content}
                        passengersId={form.ids.passengers}
                        nameId={form.ids.name}
                        phoneId={form.ids.phone}
                        infoId={form.ids.additionalInfo}
                        passengersValue={form.passengers()}
                        nameValue={form.name()}
                        phoneValue={form.phone()}
                        infoValue={form.additionalInfo()}
                        onPassengersChange={form.setPassengers}
                        onNameChange={form.setName}
                        onPhoneChange={form.setPhone}
                        onInfoChange={form.setAdditionalInfo}
                        passengersError={form.errors().passengers}
                        nameError={form.errors().name}
                        phoneError={form.errors().phone}
                    />

                    <Show when={props.showDiscount}>
                        <div class={`relative flex items-center gap-3 p-3 border rounded-md ${colorMap.discountBg[accentColor()]} mt-4 mb-10 transition-colors`}>
                            <input
                                id={form.ids.applyDiscount}
                                name="apply-discount"
                                type="checkbox"
                                checked={form.applyDiscount()}
                                onChange={(e) => form.setApplyDiscount(e.currentTarget.checked)}
                                class={`h-5 w-5 rounded border-gray-300 cursor-pointer ${colorMap.discountCheckbox[accentColor()]}`}
                            />
                            <label for={form.ids.applyDiscount} class="font-medium text-gray-800 select-none text-sm cursor-pointer">
                                {props.content.applyDiscountLabel}
                            </label>
                        </div>
                    </Show>

                    <div class="sticky bottom-0 -mx-6 -mb-8 sm:-mx-8 bg-white/90 backdrop-blur-md p-4 border-t border-gray-200 rounded-b-xl z-20">
                        <Button
                            type="submit"
                            isLoading={form.loading()}
                            fullWidth
                            variant={accentColor() === 'red' ? 'danger' : 'primary'}
                            size="lg"
                        >
                            {props.car ? 'Dieses Auto buchen' : props.content.checkAvailability}
                        </Button>
                    </div>
                </form>
            </Show>
        </div>
    );
};

export default UniversalBookingForm;