"use client";

import { useEffect, useState, useCallback, useRef } from "react";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import Image from "next/image";
import Icon from "@/components/ui/icon";
import CatalogSidebar from "@/app/catalog/components/CatalogSidebar";
import Link from "next/link";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Sliders, X, ArrowLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import useApiClient from "@/hooks/useApiClient";
import { formatMinCost, formatSpeed, formatWidth, getImageUrl } from "@/lib/utils";
import { useSearchParams, useRouter, usePathname } from "next/navigation";

export interface CatalogFilters {
    search: string;
    lengthRange: [number, number];
    priceRange: [number, number];
    yearRange: [number, number];
    adults: number;
    children: number;
    paymentType: string;
    quickBooking: boolean;
    hasToilet: boolean;
    date: Date | null;
    departureTime: string;
    arrivalTime: string;
}

export const defaultFilters: CatalogFilters = {
    lengthRange: [7, 50],
    priceRange: [3000, 200000],
    yearRange: [1991, 2025],
    adults: 0,
    children: 0,
    paymentType: "all",
    quickBooking: false,
    hasToilet: false,
    search: "",
    date: null,
    departureTime: "12:00",
    arrivalTime: "13:00",
};

export default function CatalogPage() {
    const [isFiltersOpen, setIsFiltersOpen] = useState(false);
    const searchParams = useSearchParams();
    const router = useRouter();
    const pathname = usePathname();

    const client = useApiClient();

    const [yachtCatalog, setYachtCatalog] = useState<CatalogFilteredResponseDto | null>(null);

    // Объединенное состояние фильтров
    const [filters, setFilters] = useState<CatalogFilters>(defaultFilters);

    // Загрузка фильтров из searchParams при монтировании и изменении URL
    useEffect(() => {
        const newFilters: CatalogFilters = { ...defaultFilters };

        const lengthMin = searchParams.get("lengthMin");
        const lengthMax = searchParams.get("lengthMax");
        if (lengthMin && lengthMax) {
            const min = parseInt(lengthMin);
            const max = parseInt(lengthMax);
            if (!isNaN(min) && !isNaN(max)) {
                newFilters.lengthRange = [min, max];
            }
        }

        const priceMin = searchParams.get("priceMin");
        const priceMax = searchParams.get("priceMax");
        if (priceMin && priceMax) {
            const min = parseInt(priceMin);
            const max = parseInt(priceMax);
            if (!isNaN(min) && !isNaN(max)) {
                newFilters.priceRange = [min, max];
            }
        }

        const yearMin = searchParams.get("yearMin");
        const yearMax = searchParams.get("yearMax");
        if (yearMin && yearMax) {
            const min = parseInt(yearMin);
            const max = parseInt(yearMax);
            if (!isNaN(min) && !isNaN(max)) {
                newFilters.yearRange = [min, max];
            }
        }

        const adultsParam = searchParams.get("adults");
        if (adultsParam) {
            newFilters.adults = parseInt(adultsParam) || 0;
        }

        const childrenParam = searchParams.get("children");
        if (childrenParam) {
            newFilters.children = parseInt(childrenParam) || 0;
        }

        const paymentTypeParam = searchParams.get("paymentType");
        if (paymentTypeParam) {
            newFilters.paymentType = paymentTypeParam;
        }

        const quickBookingParam = searchParams.get("quickBooking");
        if (quickBookingParam) {
            newFilters.quickBooking = quickBookingParam === "true";
        }

        const hasToiletParam = searchParams.get("hasToilet");
        if (hasToiletParam) {
            newFilters.hasToilet = hasToiletParam === "true";
        }

        const searchParam = searchParams.get("search");
        if (searchParam) {
            newFilters.search = searchParam;
        }

        const dateParam = searchParams.get("date");
        if (dateParam) {
            const parsedDate = new Date(dateParam);
            if (!isNaN(parsedDate.getTime())) {
                newFilters.date = parsedDate;
            }
        }

        const departureTimeParam = searchParams.get("departureTime");
        if (departureTimeParam) {
            newFilters.departureTime = departureTimeParam;
        }

        const arrivalTimeParam = searchParams.get("arrivalTime");
        if (arrivalTimeParam) {
            newFilters.arrivalTime = arrivalTimeParam;
        }

        setFilters(newFilters);
    }, [searchParams]);

    // Функция для сохранения фильтров в searchParams
    const handleApplyFilters = () => {
        const params = new URLSearchParams();

        // Сохраняем только нестандартные значения
        if (filters.lengthRange[0] !== defaultFilters.lengthRange[0] || filters.lengthRange[1] !== defaultFilters.lengthRange[1]) {
            params.set("lengthMin", filters.lengthRange[0].toString());
            params.set("lengthMax", filters.lengthRange[1].toString());
        }

        if (filters.priceRange[0] !== defaultFilters.priceRange[0] || filters.priceRange[1] !== defaultFilters.priceRange[1]) {
            params.set("priceMin", filters.priceRange[0].toString());
            params.set("priceMax", filters.priceRange[1].toString());
        }

        if (filters.yearRange[0] !== defaultFilters.yearRange[0] || filters.yearRange[1] !== defaultFilters.yearRange[1]) {
            params.set("yearMin", filters.yearRange[0].toString());
            params.set("yearMax", filters.yearRange[1].toString());
        }

        if (filters.adults > 0) {
            params.set("adults", filters.adults.toString());
        }

        if (filters.children > 0) {
            params.set("children", filters.children.toString());
        }

        if (filters.paymentType !== defaultFilters.paymentType) {
            params.set("paymentType", filters.paymentType);
        }

        if (filters.quickBooking) {
            params.set("quickBooking", "true");
        }

        if (filters.hasToilet) {
            params.set("hasToilet", "true");
        }

        if (filters.search) {
            params.set("search", filters.search);
        }

        if (filters.date) {
            params.set("date", filters.date.toISOString());
        }

        if (filters.departureTime !== defaultFilters.departureTime) {
            params.set("departureTime", filters.departureTime);
        }

        if (filters.arrivalTime !== defaultFilters.arrivalTime) {
            params.set("arrivalTime", filters.arrivalTime);
        }

        // Сохраняем сортировку, если она установлена
        const sortByPrice = searchParams.get("sortByPrice");
        if (sortByPrice) {
            params.set("sortByPrice", sortByPrice);
        }

        // Обновляем URL без прокрутки страницы
        const newUrl = params.toString()
            ? `${pathname}?${params.toString()}`
            : pathname;
        router.replace(newUrl, { scroll: false });
    };

    const handleReset = () => {
        setFilters(defaultFilters);
        // Очищаем URL параметры без прокрутки страницы
        router.replace(pathname, { scroll: false });
    };


    useEffect(() => {
        (async () => {
            const allParams: Record<string, string> = {
                search: searchParams.get("search") ?? "",
                minLength: searchParams.get("lengthMin") ?? "",
                maxLength: searchParams.get("lengthMax") ?? "",
                minPrice: searchParams.get("priceMin") ?? "",
                maxPrice: searchParams.get("priceMax") ?? "",
                minYear: searchParams.get("yearMin") ?? "",
                maxYear: searchParams.get("yearMax") ?? "",
                guests: searchParams.get("adults") && searchParams.get("children") ? `${Number(searchParams.get("adults")) + Number(searchParams.get("children"))}` : "",
                paymentType: searchParams.get("paymentType") ?? "",
                quickBooking: searchParams.get("quickBooking") ?? "",
                hasToilet: searchParams.get("hasToilet") ?? "",
                date: searchParams.get("date") ?? "",
                departureTime: searchParams.get("departureTime") ?? "",
                arrivalTime: searchParams.get("arrivalTime") ?? "",
                sortByPrice: searchParams.get("sortByPrice") ?? "",
            };

            const params = Object.fromEntries(
                Object.entries(allParams).filter(([_, value]) => value !== "")
            );

            const response = await client.get<CatalogFilteredResponseDto>("/catalog/filter/", {
                params,
            });

            setYachtCatalog(response.data);
        })();
    }, [searchParams])

    return (
        <main className="bg-[#f4f4f4]">
            <div className="container max-w-6xl mx-auto px-4 py-6">
                {/* Breadcrumbs - скрыты на мобильных */}
                <div className="hidden lg:flex mb-4 text-sm text-[#999999] items-center gap-[16px]">
                    <Link href="/">
                        <span className="cursor-pointer hover:text-[#333333] transition-colors">
                            Аренда яхты
                        </span>
                    </Link>
                    <span>&gt;</span>
                    <span className="text-[#333333]">Каталог яхт</span>
                </div>

                {/* Мобильная навигационная панель */}
                <div className="lg:hidden mb-4">
                    <div className="flex items-center gap-3">
                        {/* Кнопка "Назад" */}
                        <Link href="/">
                            <button className="flex-shrink-0 w-8 h-8 flex items-center justify-center">
                                <ArrowLeft
                                    size={32}
                                    className="text-[#333333] font-bold"
                                />
                            </button>
                        </Link>

                        {/* Текстовый блок */}
                        <div className="flex-1 min-w-0">
                            <div className="font-bold text-[#333333] text-base truncate">
                                Балаклава
                            </div>
                            <div className="text-sm text-[#999999] truncate">
                                Когда? · С кем?
                            </div>
                        </div>

                        {/* Кнопка "Фильтры" */}
                        <Button
                            onClick={() => setIsFiltersOpen(true)}
                            className="flex-shrink-0 w-[56px] h-[56px] rounded-full bg-white hover:bg-gray-50 text-black p-0"
                        >
                            <Sliders size={20} className="text-[#333333]" />
                        </Button>
                    </div>
                </div>

                <div className="flex flex-col lg:flex-row gap-[74px]">
                    {/* Sidebar - скрыт на мобильных, виден на десктопе */}
                    <div className="hidden lg:block w-full lg:w-[260px] flex-shrink-0">
                        <CatalogSidebar
                            filters={filters}
                            setFilters={setFilters}
                            onApply={handleApplyFilters}
                            onReset={handleReset}
                        />
                    </div>

                    {/* Мобильное модальное окно фильтров */}
                    {isFiltersOpen && (
                        <div className="fixed inset-0 z-50 lg:hidden">
                            {/* Overlay */}
                            <div
                                className="absolute inset-0 bg-black/50"
                                onClick={() => setIsFiltersOpen(false)}
                            />
                            {/* Модальное окно */}
                            <div className="absolute inset-0 bg-white overflow-y-auto">
                                <div className="sticky top-0 bg-white border-b border-gray-200 p-4 flex items-center justify-between z-10">
                                    <h2 className="text-lg font-bold text-[#333333]">
                                        Фильтры
                                    </h2>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        onClick={() => setIsFiltersOpen(false)}
                                        className="h-8 w-8"
                                    >
                                        <X size={20} />
                                    </Button>
                                </div>
                                <div className="p-4">
                                    <CatalogSidebar
                                        filters={filters}
                                        setFilters={setFilters}
                                        onApply={() => {
                                            handleApplyFilters();
                                            setIsFiltersOpen(false);
                                        }}
                                        onReset={handleReset}
                                    />
                                </div>
                            </div>
                        </div>
                    )}

                    {/* Main Content */}
                    <div className="flex-1">
                        {/* Header */}
                        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-end mb-6">
                            <div className="w-full lg:w-auto">
                                <h1 className="text-2xl md:text-3xl font-bold text-[#333333] mb-4">
                                    Аренда яхт
                                </h1>
                                <p className="hidden lg:block text-lg text-[#333333]">
                                    Доступно яхт:{" "}
                                    <span className="text-[#b2b2b2]">
                                        {yachtCatalog?.total}
                                    </span>
                                </p>
                            </div>
                            <div className="flex items-center gap-1 w-full sm:w-auto">
                                <div className="text-base text-[#999999]">
                                    Сортировка:
                                </div>
                                <Select 
                                    value={searchParams.get("sortByPrice") || "default"}
                                    onValueChange={(value) => {
                                        const params = new URLSearchParams(searchParams.toString());
                                        if (value === "default") {
                                            params.delete("sortByPrice");
                                        } else {
                                            params.set("sortByPrice", value);
                                        }
                                        const newUrl = params.toString()
                                            ? `${pathname}?${params.toString()}`
                                            : pathname;
                                        router.replace(newUrl, { scroll: false });
                                    }}
                                >
                                    <SelectTrigger
                                        className="w-full"
                                        variant="ghost"
                                    >
                                        <SelectValue placeholder="Сортировка" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="default">
                                            По умолчанию
                                        </SelectItem>
                                        <SelectItem value="asc">
                                            Цена: по возрастанию
                                        </SelectItem>
                                        <SelectItem value="desc">
                                            Цена: по убыванию
                                        </SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>

                        {/* Yacht Grid */}
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            {yachtCatalog && (<>
                                {yachtCatalog.items.map((yacht) => (
                                    <Link
                                        key={yacht.id}
                                        href={`/catalog/${yacht.id ?? 0}`}
                                        className="block"
                                    >
                                        <Card className="overflow-hidden bg-white text-gray-900 border border-gray-200 cursor-pointer transition-all duration-200 hover:shadow-lg">
                                            <CardHeader className="p-0 relative">
                                                <div className="relative">
                                                    <Image
                                                        src={getImageUrl(yacht.mainImageUrl)}
                                                        alt={yacht.name}
                                                        width={400}
                                                        height={250}
                                                        className="w-full h-48 object-cover"
                                                    />
                                                    {/* Badge Overlay */}
                                                    {!yacht.hasQuickRent && (
                                                        <div className="absolute top-3 left-3">
                                                            <div className="flex items-center justify-center bg-black/40 text-white px-3 py-1 rounded-lg text-sm gap-1">
                                                                <Icon
                                                                    size={16}
                                                                    name="restart"
                                                                />
                                                                <span>
                                                                    По запросу
                                                                </span>
                                                            </div>
                                                        </div>
                                                    )}
                                                </div>
                                            </CardHeader>
                                            <CardContent className="p-4">
                                                <div className="flex justify-between gap-4">
                                                    {/* Левая колонка - название и длина */}
                                                    <div className="space-y-2">
                                                        <h3 className="font-bold text-lg">
                                                            {yacht.name}
                                                        </h3>
                                                        <div className="flex items-center gap-1 text-sm text-gray-600">
                                                            <Icon
                                                                size={16}
                                                                name="width"
                                                            />
                                                            <span>
                                                                {formatWidth(yacht.length)}
                                                            </span>
                                                        </div>
                                                    </div>

                                                    {/* Правая колонка - цена и футы */}
                                                    <div className="space-y-2 text-right">
                                                        <p className="text-lg font-bold text-black">
                                                            {formatMinCost(yacht.minCost)} / час
                                                        </p>
                                                        <div className="flex items-center gap-1 text-sm text-gray-600 justify-end">
                                                            <Icon
                                                                size={16}
                                                                name="anchor"
                                                            />
                                                            <span>
                                                                {formatSpeed(yacht.speed)}
                                                            </span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </CardContent>
                                        </Card>
                                    </Link>
                                ))}
                            </>)}
                        </div>
                    </div>
                </div>
            </div>
        </main>
    );
}
