import React, { useEffect, useState, useCallback } from 'react';
import { useLocation, useNavigate, Link } from 'react-router-dom';
import { listMedia, mediaTypes, getFileUrl } from '../services/pocketbaseService';
import TiltedCard from '../components/reactbits/Components/TiltedCard/TiltedCard';
import { useAuth } from '../contexts/AuthContext';
import Select from 'react-select';

const typeOptions = [
    { value: '', label: 'Все типы' },
    ...Object.entries(mediaTypes).map(([key, value]) => ({ value: key, label: value.label }))
];

const sortOptions = [
    { value: '-created', label: 'Новые сначала' },
    { value: 'created', label: 'Старые сначала' },
    { value: 'title', label: 'По названию (А-Я)' },
    { value: '-title', label: 'По названию (Я-А)' },
    { value: '-average_rating', label: 'По рейтингу (сначала высокие)' },
    { value: 'average_rating', label: 'По рейтингу (сначала низкие)' },
    { value: '-review_count', label: 'По количеству рецензий (сначала больше)' },
    { value: 'review_count', label: 'По количеству рецензий (сначала меньше)' },
    { value: '-release_date', label: 'По дате выхода (сначала новые)' },
    { value: 'release_date', label: 'По дате выхода (сначала старые)' }
];

const yearFilterOptions = [
    { value: '', label: 'Любой год' },
    { value: '2025', label: '2025' },
    { value: '2024', label: '2024' },
    { value: '2023', label: '2023' },
    { value: '2022', label: '2022' },
    { value: '2021', label: '2021' },
    { value: '2020', label: '2020' },
    { value: 'older', label: 'Раньше 2020' }
];

const CatalogPage = () => {
    const location = useLocation();
    const navigate = useNavigate();
    const { userProfile } = useAuth();

    const [mediaList, setMediaList] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [page, setPage] = useState(1);
    const [totalPages, setTotalPages] = useState(1);
    const [totalItems, setTotalItems] = useState(0);

    // State for filters and sorting, initialized from URL params
    const [selectedType, setSelectedType] = useState(typeOptions[0]);
    const [selectedSort, setSelectedSort] = useState(sortOptions[0]);
    const [selectedYear, setSelectedYear] = useState(yearFilterOptions[0]);

    // Custom styles for react-select
    const selectStyles = {
        control: (provided, state) => ({
            ...provided,
            backgroundColor: '#2a2a2a', // campfire-dark
            borderColor: state.isFocused ? '#f59e0b' : '#4a4a4a', // campfire-amber / campfire-ash/30
            color: '#e0e0e0', // campfire-light
            boxShadow: state.isFocused ? '0 0 0 1px #f59e0b' : 'none',
            '&:hover': {
                borderColor: state.isFocused ? '#f59e0b' : '#6a6a6a', // campfire-amber / campfire-ash/60
            },
            cursor: 'pointer',
        }),
        singleValue: (provided) => ({
            ...provided,
            color: '#e0e0e0', // campfire-light
        }),
        input: (provided) => ({
            ...provided,
            color: '#e0e0e0', // campfire-light
        }),
        placeholder: (provided) => ({
            ...provided,
            color: '#a0a0a0', // campfire-ash
        }),
        menu: (provided) => ({
            ...provided,
            backgroundColor: '#2a2a2a', // campfire-dark
            zIndex: 9999, // Ensure dropdown is above other content
        }),
        option: (provided, state) => ({
            ...provided,
            backgroundColor: state.isFocused ? '#3a3a3a' : '#2a2a2a', // Darker hover / campfire-dark
            color: state.isSelected ? '#f59e0b' : '#e0e0e0', // campfire-amber / campfire-light
            cursor: 'pointer',
        }),
    };

    // Effect to read URL params on mount and location change
    useEffect(() => {
        const params = new URLSearchParams(location.search);
        const typeParam = params.get('type') || '';
        const sortParam = params.get('sort') || '-created';
        const pageParam = parseInt(params.get('page') || '1', 10);
        const yearParam = params.get('year') || '';

        const initialType = typeOptions.find(opt => opt.value === typeParam) || typeOptions[0];
        const initialSort = sortOptions.find(opt => opt.value === sortParam) || sortOptions[0];
        const initialYear = yearFilterOptions.find(opt => opt.value === yearParam) || yearFilterOptions[0];

        setSelectedType(initialType);
        setSelectedSort(initialSort);
        setSelectedYear(initialYear);
        setPage(pageParam);

        // Initial data fetch based on URL params
        fetchMediaData(initialType.value, initialSort.value, pageParam);
    }, [location.search]);

    // Function to update URL search params
    const updateUrlParams = useCallback((type, sort, page, year) => {
        const params = new URLSearchParams();
        if (type) params.set('type', type);
        if (sort) params.set('sort', sort);
        if (page > 1) params.set('page', page);
        if (year) params.set('year', year);
        navigate({ search: params.toString() }, { replace: true });
    }, [navigate]);

    // Function to fetch media data
    const fetchMediaData = useCallback(async (type, sort, pageNum) => {
        try {
            setLoading(true);
            setError(null);

            // Создаем дополнительные фильтры
            const additionalFilters = [];
            
            // Фильтр по году
            if (selectedYear.value) {
                if (selectedYear.value === 'older') {
                    additionalFilters.push(`release_date < "2020-01-01 00:00:00"`);
                } else {
                    const year = parseInt(selectedYear.value);
                    const startDate = `${year}-01-01 00:00:00`;
                    const endDate = `${year + 1}-01-01 00:00:00`;
                    additionalFilters.push(`release_date >= "${startDate}" && release_date < "${endDate}"`);
                }
            }

            // Объединяем все фильтры
            const filterString = additionalFilters.length > 0 ? additionalFilters.join(' && ') : '';

            console.log('Fetching with filters:', {
                type,
                sort,
                pageNum,
                filterString,
                selectedYear: selectedYear.value
            });

            const { data, count, totalPages: fetchedTotalPages } = await listMedia(
                type || null,
                pageNum,
                20,
                userProfile,
                false,
                true,
                sort,
                filterString
            );

            setMediaList(data);
            setTotalItems(count);
            setTotalPages(fetchedTotalPages);

        } catch (err) {
            console.error('Error fetching catalog media:', err);
            setError('Не удалось загрузить список медиа.');
        } finally {
            setLoading(false);
        }
    }, [userProfile, selectedYear]);

    // Effect to refetch data when filters/sort/page change
    useEffect(() => {
        fetchMediaData(selectedType.value, selectedSort.value, page);
    }, [selectedType.value, selectedSort.value, page, fetchMediaData]);

    const handleTypeChange = useCallback((selectedOption) => {
        setSelectedType(selectedOption);
        setPage(1);
        fetchMediaData(selectedOption.value, selectedSort.value, 1);
    }, [selectedSort.value, fetchMediaData]);

    const handleSortChange = useCallback((selectedOption) => {
        setSelectedSort(selectedOption);
        setPage(1);
        fetchMediaData(selectedType.value, selectedOption.value, 1);
    }, [selectedType.value, fetchMediaData]);

    const handleYearChange = useCallback((selectedOption) => {
        setSelectedYear(selectedOption);
        setPage(1);
        fetchMediaData(selectedType.value, selectedSort.value, 1);
    }, [selectedType.value, selectedSort.value, fetchMediaData]);

    const handlePageChange = useCallback((newPage) => {
        if (newPage >= 1 && newPage <= totalPages) {
            setPage(newPage);
            fetchMediaData(selectedType.value, selectedSort.value, newPage);
        }
    }, [selectedType.value, selectedSort.value, totalPages, fetchMediaData]);

    if (loading) {
        return (
            <div className="min-h-screen bg-campfire-dark pt-20 flex justify-center items-center">
                <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-campfire-amber"></div>
            </div>
        );
    }

    if (error) {
        return (
            <div className="min-h-screen bg-campfire-dark pt-20 flex justify-center items-center">
                <div className="bg-status-error/20 text-status-error p-4 rounded-lg text-center">
                    {error}
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-campfire-dark pt-20 container-custom py-8">
            <h1 className="text-3xl font-bold mb-6 text-campfire-light">Каталог медиа</h1>

            {/* Filter and Sort Controls */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-8">
                <div>
                    <label htmlFor="type-select" className="block mb-2 text-campfire-light text-sm font-medium">
                        Тип медиа:
                    </label>
                    <Select
                        id="type-select"
                        options={typeOptions}
                        value={selectedType}
                        onChange={handleTypeChange}
                        styles={selectStyles}
                        isSearchable={false}
                        classNamePrefix="react-select"
                    />
                </div>
                <div>
                    <label htmlFor="year-select" className="block mb-2 text-campfire-light text-sm font-medium">
                        Год выхода:
                    </label>
                    <Select
                        id="year-select"
                        options={yearFilterOptions}
                        value={selectedYear}
                        onChange={handleYearChange}
                        styles={selectStyles}
                        isSearchable={false}
                        classNamePrefix="react-select"
                    />
                </div>
                <div>
                    <label htmlFor="sort-select" className="block mb-2 text-campfire-light text-sm font-medium">
                        Сортировка:
                    </label>
                    <Select
                        id="sort-select"
                        options={sortOptions}
                        value={selectedSort}
                        onChange={handleSortChange}
                        styles={selectStyles}
                        isSearchable={false}
                        classNamePrefix="react-select"
                    />
                </div>
            </div>

            {mediaList.length > 0 ? (
                <>
                    <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-8 md:gap-15">
                        {mediaList.map((mediaItem) => (
                            <Link 
                                key={mediaItem.id} 
                                to={`/media/${mediaItem.path}`}
                                className="block group"
                            >
                                <TiltedCard 
                                    imageSrc={mediaItem.poster ? getFileUrl(mediaItem, 'poster', { thumb: '1000x1000' }) : 'https://via.placeholder.com/300x450'} 
                                    captionText={mediaItem.title}
                                    rating={mediaItem.average_rating}
                                    releaseDate={mediaItem.release_date}
                                    containerHeight="360px"
                                    containerWidth="100%"
                                    imageHeight="360px"
                                    imageWidth="240px"
                                />
                            </Link>
                        ))}
                    </div>

                    {/* Pagination */}
                    {totalPages > 1 && (
                        <div className="flex justify-center items-center space-x-4 mt-8 text-campfire-light">
                            <button
                                onClick={() => handlePageChange(page - 1)}
                                disabled={page === 1}
                                className="btn-secondary disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                Предыдущая
                            </button>
                            <span>
                                Страница {page} из {totalPages}
                            </span>
                            <button
                                onClick={() => handlePageChange(page + 1)}
                                disabled={page === totalPages}
                                className="btn-secondary disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                Следующая
                            </button>
                        </div>
                    )}
                </>
            ) : (
                <p className="text-campfire-ash text-center py-8">
                    По вашему запросу ничего не найдено.
                </p>
            )}
        </div>
    );
};

export default CatalogPage;
