import { createSignal, createMemo, Show, For } from 'solid-js';
import { FaSolidChevronLeft, FaSolidChevronRight } from 'solid-icons/fa';
import { UniversalBookingForm } from '@/components/booking/UniversalBookingForm';
import { heroContent } from '@/components/home/hero/HeroContent';
import Notification from '@/components/home/slider/Notification';
import {
    type Car,
    germanCarsSliderContent as contentData,
    transformSliderDataToCar
} from '@/components/home/slider/SliderContent';
import { sliderService } from '@/lib/sliderService';
import { authService } from '@/lib/authService';
import type { CarsSliderProps, CarsSliderText } from '@/types/globalInterfaces';

import { SolidModal } from '@/components/base/Buttons';
import CarSliderCard from './CarSliderCard';
import CarDetailsCard from './CarDetailsCard';

const componentText: CarsSliderText = {
    mainTitle: 'Verfügbare Fahrzeuge',
    subtitle: 'Wählen Sie die perfekte Option für Ihren Transfer',
    previousButtonAlt: 'Vorherige Karten',
    nextButtonAlt: 'Nächste Karten',
    selectButton: 'Details Ansehen',
    goToSlide: 'Gehe zu Folie',
};

const CarsSlider = (props: CarsSliderProps) => {
    const text = componentText;

    const [currentSlide, setCurrentSlide] = createSignal(0);
    const [direction, setDirection] = createSignal<'left' | 'right'>('right');
    const [isModalOpen, setIsModalOpen] = createSignal(false);
    const [selectedCar, setSelectedCar] = createSignal<Car | null>(null);
    const [notification, setNotification] = createSignal<{
        message: string;
        type: 'success' | 'error';
    } | null>(null);
    const [modalView, setModalView] = createSignal<'details' | 'form'>('details');
    const [isMobile, setIsMobile] = createSignal<boolean>(false);

    // Используем данные из пропсов с проверкой на определенность
    const cars = () => props.cars || [];

    const cardsPerPage = createMemo(() => (isMobile() ? 1 : 3));
    const totalSlides = createMemo(() => Math.ceil(cars().length / cardsPerPage()));

    const visibleCars = createMemo(() => {
        const startIndex = currentSlide() * cardsPerPage();
        const visible: Car[] = [];
        for (let i = 0; i < cardsPerPage(); i++) {
            const carIndex = startIndex + i;
            if (carIndex < cars().length) {
                visible.push(cars()[carIndex]);
            }
        }
        return visible;
    });

    // handleSuccess и handleError больше не используются, так как
    // используется событийная модель через booking-success и booking-error

    const goToNext = () => {
        setDirection('right');
        setCurrentSlide((prev) => (prev + 1) % totalSlides());
    };

    const goToPrevious = () => {
        setDirection('left');
        setCurrentSlide((prev) => (prev - 1 + totalSlides()) % totalSlides());
    };

    const goToSlide = (index: number) => {
        setDirection(index > currentSlide() ? 'right' : 'left');
        setCurrentSlide(index);
    };

    const handleOpenDetails = (car: Car) => {
        setSelectedCar(car);
        setModalView('details');
        setIsModalOpen(true);
    };

    const handleShowBookingForm = () => {
        setModalView('form');
    };

    const handleCloseModal = () => {
        setIsModalOpen(false);
        setNotification(null);
        setTimeout(() => {
            setSelectedCar(null);
            setModalView('details');
        }, 300);
    };

    return (
        <>
            <section class="bg-white py-12 sm:py-16">
                <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div class="text-center mb-8">
                        <h2 class="text-3xl sm:text-4xl md:text-5xl font-bold tracking-tight text-gray-900">
                            {text.mainTitle}
                        </h2>
                        <p class="mt-4 sm:mt-6 text-base sm:text-lg leading-7 text-gray-600 max-w-3xl mx-auto">
                            {text.subtitle}
                        </p>
                    </div>

                    <div class="max-w-xl mx-auto mb-8 h-4 flex items-center justify-center">
                        <Show when={notification()}>
                            {(notification) => (
                                <Notification
                                    message={notification().message}
                                    type={notification().type}
                                    onClose={() => setNotification(null)}
                                />
                            )}
                        </Show>
                    </div>

                    {/*
                        Основной контейнер слайдера
                        Проверяем, есть ли данные для отображения
                    */}
                    {props.cars && props.cars.length > 0 ? (
                        <div class="relative w-full max-w-7xl mx-auto">
                            <div class="relative">
                                {/* Контейнер навигации и карточек */}
                                <div class="flex items-center justify-center">

                                    {/* Кнопка "Назад" (Custom HTML Button) */}
                                    <button
                                        onClick={goToPrevious}
                                        aria-label={text.previousButtonAlt}
                                        class={`
                                            absolute z-20 top-1/2 -translate-y-1/2
                                            w-12 h-12 rounded-full
                                            flex items-center justify-center
                                            bg-white text-gray-700
                                            shadow-[0_4px_12px_rgba(0,0,0,0.12)] border border-gray-100
                                            transition-all duration-300 ease-out
                                            hover:bg-gray-50 hover:text-blue-600 hover:shadow-[0_8px_16px_rgba(0,0,0,0.15)] hover:scale-110 hover:border-gray-200
                                            active:scale-95 active:shadow-sm
                                            cursor-pointer
                                            focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2
                                            ${isMobile() ? '-left-2' : '-left-6'}
                                        `}
                                    >
                                        <FaSolidChevronLeft size={18} />
                                    </button>

                                    {/* Контейнер карточек */}
                                    <div class="flex justify-center items-stretch gap-4 sm:gap-6 w-full px-4 sm:px-12 overflow-hidden">
                                        <For each={visibleCars()}>
                                            {(car) => (
                                                <div class="flex-1 max-w-lg transition-all duration-500 ease-in-out animate-fade-in">
                                                    <CarSliderCard
                                                        car={car}
                                                        onDetailsClick={() => handleOpenDetails(car)}
                                                    />
                                                </div>
                                            )}
                                        </For>
                                    </div>

                                    {/* Кнопка "Вперед" (Custom HTML Button) */}
                                    <button
                                        onClick={goToNext}
                                        aria-label={text.nextButtonAlt}
                                        class={`
                                            absolute z-20 top-1/2 -translate-y-1/2
                                            w-12 h-12 rounded-full
                                            flex items-center justify-center
                                            bg-white text-gray-700
                                            shadow-[0_4px_12px_rgba(0,0,0,0.12)] border border-gray-100
                                            transition-all duration-300 ease-out
                                            hover:bg-gray-50 hover:text-blue-600 hover:shadow-[0_8px_16px_rgba(0,0,0,0.15)] hover:scale-110 hover:border-gray-200
                                            active:scale-95 active:shadow-sm
                                            cursor-pointer
                                            focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2
                                            ${isMobile() ? '-right-2' : '-right-6'}
                                        `}
                                    >
                                        <FaSolidChevronRight size={18} />
                                    </button>
                                </div>

                                {/* Индикаторы (точки) */}
                                <div class="flex mt-8 space-x-2.5 justify-center">
                                    <For each={Array.from({ length: totalSlides() })}>
                                        {(_, index) => (
                                            <button
                                                onClick={() => goToSlide(index())}
                                                class={`
                                                    h-2.5 rounded-full transition-all duration-300 ease-out cursor-pointer
                                                    focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-1
                                                    ${
                                                    currentSlide() === index()
                                                        ? 'bg-blue-600 w-8 shadow-md' // Активная точка
                                                        : 'bg-gray-300 w-2.5 hover:bg-gray-400 hover:scale-110'
                                                }
                                                `}
                                                aria-label={`${text.goToSlide} ${index() + 1}`}
                                            />
                                        )}
                                    </For>
                                </div>
                            </div>
                        </div>
                    ) : (
                        <div class="text-center py-12">
                            <p class="text-gray-600">Keine Fahrzeuge verfügbar</p>
                        </div>
                    )}
                </div>
            </section>

            <SolidModal
                isOpen={isModalOpen()}
                onClose={handleCloseModal}
                title={modalView() === 'details' ? 'Fahrzeugdetails' : 'Ihre Anfrage'}
                size="lg"
            >
                <Show when={selectedCar()}>
                    {(car) => (
                        <Show
                            when={modalView() === 'details'}
                            fallback={
                                <div class="p-6">
                                    <UniversalBookingForm
                                        car={car()}
                                        content={heroContent}
                                        formType="slider"
                                        accentColor="blue"
                                    />
                                </div>
                            }
                        >
                            <CarDetailsCard
                                car={car()}
                                onBookingClick={handleShowBookingForm}
                            />
                        </Show>
                    )}
                </Show>
            </SolidModal>
        </>
    );
};

export default CarsSlider;