import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { listMedia, deleteMedia, mediaTypes } from '../../services/pocketbaseService';
import Modal from '../../components/common/Modal';
import MediaForm from '../../components/admin/MediaForm';
import TMDBImportModal from '../../components/admin/TMDBImportModal';
import AIReviewModal from '../../components/admin/AIReviewModal';
import { FaEdit, FaTrashAlt, FaPlus, FaTv, FaDownload, FaRobot } from 'react-icons/fa'; // Import FaTv icon

const AdminMediaPage = () => {
    const navigate = useNavigate();
    const { user, userProfile, loading: authLoading } = useAuth();

    const [mediaList, setMediaList] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    const [isAddModalOpen, setIsAddModalOpen] = useState(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [isImportModalOpen, setIsImportModalOpen] = useState(false);
    const [mediaToEdit, setMediaToEdit] = useState(null);
    const [filterType, setFilterType] = useState(''); // State for type filter
    const [filterPublished, setFilterPublished] = useState(''); // State for published filter ('', 'true', 'false')
    const [isAIReviewModalOpen, setIsAIReviewModalOpen] = useState(false);
    const [selectedMedia, setSelectedMedia] = useState(null);

    // Check if the current user is admin
    const isAdmin = userProfile?.role === 'admin';

    // Use useCallback to memoize loadMediaData
    const loadMediaData = useCallback(async () => {
        try {
            setLoading(true);
            setError(null);
            // Pass filterType and filterPublished to listMedia
            const data = await listMedia(filterType || null, 1, 50, user, false, filterPublished === '' ? null : filterPublished === 'true'); // Fetch up to 50 items for admin view, not popular, filter published based on state
            setMediaList(data.data || []);
        } catch (err) {
            console.error('Error loading media data:', err);
            setError('Не удалось загрузить данные контента.');
        } finally {
            setLoading(false);
        }
    }, [filterType, filterPublished, user]); // Depend on filter states and user

    useEffect(() => {
        console.log('AdminMediaPage mounted, user:', user);

        // Wait for auth to finish loading before checking user/profile
        if (authLoading) {
            console.log('AdminMediaPage: Auth loading...');
            return;
        }

        // Redirect if not admin (AdminRoute should handle this, but double-check)
        if (!user || !isAdmin) {
             console.warn('AdminMediaPage: User is not admin, redirecting.');
             navigate('/admin'); // Redirect to admin dashboard or login
             return;
        }

        // Load data if user is admin
        if (user && isAdmin) {
            loadMediaData();
        }

    }, [user, userProfile, authLoading, navigate, isAdmin, loadMediaData]); // Depend on auth states, navigate, loadMediaData

    // Reload data when filters change
    useEffect(() => {
        if (user && isAdmin) {
            loadMediaData();
        }
    }, [filterType, filterPublished, user, isAdmin, loadMediaData]);


    const handleAddMedia = () => {
        setMediaToEdit(null); // Ensure we are adding, not editing
        setIsAddModalOpen(true);
    };

    const handleEditMedia = (media) => {
        setMediaToEdit(media); // Set media to edit
        setIsEditModalOpen(true);
    };

    const handleDeleteMedia = async (mediaId) => {
        if (!window.confirm('Вы уверены, что хотите удалить этот контент? Это также удалит все связанные с ним рецензии и сезоны!')) {
            return;
        }
        try {
            setLoading(true); // Show main loading indicator
            setError(null); // Clear main error
            await deleteMedia(mediaId);
            loadMediaData(); // Reload the list after deletion
        } catch (err) {
            console.error('Error deleting media:', err);
            setError('Не удалось удалить контент.');
            setLoading(false); // Hide loading on error
        }
    };

    const handleFormSuccess = () => {
        setIsAddModalOpen(false);
        setIsEditModalOpen(false);
        setMediaToEdit(null);
        loadMediaData(); // Reload the list after add/edit
    };

    const handleFormCancel = () => {
        setIsAddModalOpen(false);
        setIsEditModalOpen(false);
        setMediaToEdit(null);
    };

    // Function to navigate to seasons page
    const handleManageSeasons = (mediaId) => {
        navigate(`/admin/media/${mediaId}/seasons`);
    };

    const handleImportSuccess = (importData) => {
        setMediaToEdit(importData);
        setIsAddModalOpen(true);
    };

    const handleAIReview = (media) => {
        setSelectedMedia(media);
        setIsAIReviewModalOpen(true);
    };

    const handleAIReviewSuccess = () => {
        setIsAIReviewModalOpen(false);
        setSelectedMedia(null);
        loadMediaData(); // Перезагружаем данные после создания рецензии
    };

    if (authLoading || loading) {
        return <div className="flex justify-center items-center h-screen text-campfire-light">Загрузка...</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>
        );
    }

    // If not admin, redirect happened in useEffect, this shouldn't be reached but as a fallback:
    if (!isAdmin) {
        return null;
    }


    return (
        <div className="container-custom py-12">
            <div className="flex justify-between items-center mb-8">
                <h1 className="text-3xl font-bold text-campfire-light">
                    Управление <span className="font-semibold text-campfire-amber">контентом</span>
                </h1>
                <div className="flex gap-4">
                    <button
                        onClick={() => setIsImportModalOpen(true)}
                        className="btn-secondary flex items-center gap-2"
                    >
                        <FaDownload />
                        <span>Импорт из TMDB</span>
                    </button>
                <button
                        onClick={() => {
                            setMediaToEdit(null);
                            setIsAddModalOpen(true);
                        }}
                        className="btn-primary flex items-center gap-2"
                >
                        <FaPlus />
                    <span>Добавить контент</span>
                </button>
                </div>
            </div>

            {/* Filters */}
            <div className="flex space-x-4 mb-6">
                {/* Type Filter */}
                <div>
                    <label htmlFor="filterType" className="block text-sm font-medium text-campfire-light mb-1">
                        Тип:
                    </label>
                    <select
                        id="filterType"
                        value={filterType}
                        onChange={(e) => setFilterType(e.target.value)}
                        className="input px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber transition-colors"
                    >
                        <option value="">Все типы</option>
                        {Object.entries(mediaTypes).map(([key, value]) => (
                            <option key={key} value={key}>{value.label}</option>
                        ))}
                    </select>
                </div>

                {/* Published Filter */}
                 <div>
                    <label htmlFor="filterPublished" className="block text-sm font-medium text-campfire-light mb-1">
                        Статус публикации:
                    </label>
                    <select
                        id="filterPublished"
                        value={filterPublished}
                        onChange={(e) => setFilterPublished(e.target.value)}
                        className="input px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber transition-colors"
                    >
                        <option value="">Все</option>
                        <option value="true">Опубликовано</option>
                        <option value="false">Не опубликовано</option>
                    </select>
                </div>
            </div>


            {mediaList.length === 0 ? (
                <div className="text-center py-8 text-campfire-light">
                    Контент не найден. Добавьте первый элемент!
                </div>
            ) : (
                <div className="overflow-x-auto custom-scrollbar"> {/* Add overflow for responsiveness */}
                    <table className="min-w-full divide-y divide-campfire-ash/20">
                        <thead className="bg-campfire-dark">
                            <tr>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-campfire-ash uppercase tracking-wider">
                                    Название
                                </th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-campfire-ash uppercase tracking-wider">
                                    Тип
                                </th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-campfire-ash uppercase tracking-wider">
                                    Опубликовано
                                </th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-campfire-ash uppercase tracking-wider">
                                    Популярное
                                </th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-campfire-ash uppercase tracking-wider">
                                    Рейтинг
                                </th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-campfire-ash uppercase tracking-wider">
                                    Обзоры
                                </th>
                                <th scope="col" className="relative px-6 py-3">
                                    <span className="sr-only">Действия</span>
                                </th>
                            </tr>
                        </thead>
                        <tbody className="bg-campfire-charcoal divide-y divide-campfire-ash/20 text-campfire-light">
                            {mediaList.map((media) => (
                                <tr key={media.id}>
                                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-campfire-light">
                                        {media.title}
                                    </td>
                                    <td className="px-6 py-4 whitespace-nowrap text-sm text-campfire-ash">
                                        {mediaTypes[media.type]?.label || media.type}
                                    </td>
                                     <td className="px-6 py-4 whitespace-nowrap text-sm">
                                        <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${media.is_published ? 'bg-status-success/20 text-status-success' : 'bg-status-error/20 text-status-error'}`}>
                                            {media.is_published ? 'Да' : 'Нет'}
                                        </span>
                                    </td>
                                     <td className="px-6 py-4 whitespace-nowrap text-sm">
                                        <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${media.is_popular ? 'bg-status-success/20 text-status-success' : 'bg-status-error/20 text-status-error'}`}>
                                            {media.is_popular ? 'Да' : 'Нет'}
                                        </span>
                                    </td>
                                    <td className="px-6 py-4 whitespace-nowrap text-sm text-campfire-ash">
                                        {media.average_rating ? media.average_rating.toFixed(1) : 'N/A'}
                                    </td>
                                    <td className="px-6 py-4 whitespace-nowrap text-sm text-campfire-ash">
                                        {media.review_count ?? 0}
                                    </td>
                                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                        <div className="flex items-center justify-end space-x-4">
                                            {/* Manage Seasons Button (only for TV/Anime) */}
                                            {(media.type === 'tv' || media.type === 'anime') && (
                                                <button
                                                    onClick={() => handleManageSeasons(media.id)}
                                                    className="text-campfire-amber hover:text-campfire-light transition-colors"
                                                    title="Управление сезонами"
                                                >
                                                    <FaTv size={18} />
                                                </button>
                                            )}
                                            {/* Edit Button */}
                                            <button
                                                onClick={() => handleEditMedia(media)}
                                                className="text-campfire-amber hover:text-campfire-light transition-colors"
                                                title="Редактировать"
                                            >
                                                <FaEdit size={18} />
                                            </button>
                                            {/* Delete Button */}
                                            <button
                                                onClick={() => handleDeleteMedia(media.id)}
                                                className="text-status-error hover:text-red-400 transition-colors"
                                                title="Удалить"
                                            >
                                                <FaTrashAlt size={18} />
                                            </button>
                                            {/* AI Review Button */}
                                            <button
                                                onClick={() => handleAIReview(media)}
                                                className="text-campfire-amber hover:text-campfire-light transition-colors"
                                                title="Создать ИИ-рецензию"
                                            >
                                                <FaRobot size={18} />
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}

            {/* Add Media Modal */}
            <Modal
                isOpen={isAddModalOpen}
                onClose={handleFormCancel}
                title="Добавить новый контент"
                size="lg" // Use lg size
            >
                <MediaForm onSuccess={handleFormSuccess} media={mediaToEdit} />
            </Modal>

            {/* Edit Media Modal */}
            <Modal
                isOpen={isEditModalOpen}
                onClose={handleFormCancel}
                title="Редактировать контент"
                size="lg" // Use lg size
            >
                {/* Pass mediaToEdit to the form */}
                <MediaForm media={mediaToEdit} onSuccess={handleFormSuccess} />
            </Modal>

            {/* Import Modal */}
            <Modal
                isOpen={isImportModalOpen}
                onClose={() => setIsImportModalOpen(false)}
                title="Импорт из TMDB"
                size="lg"
            >
                <TMDBImportModal
                    onClose={() => setIsImportModalOpen(false)}
                    onImport={handleImportSuccess}
                />
            </Modal>

            {/* AI Review Modal */}
            <Modal
                isOpen={isAIReviewModalOpen}
                onClose={() => setIsAIReviewModalOpen(false)}
                title="ИИ-рецензия"
                size="lg"
            >
                {selectedMedia && (
                    <AIReviewModal
                        media={selectedMedia}
                        onClose={() => setIsAIReviewModalOpen(false)}
                        onSuccess={handleAIReviewSuccess}
                    />
                )}
            </Modal>
        </div>
    );
};

export default AdminMediaPage;
