import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { getSeasons, createSeason, updateSeason, deleteSeason, getFileUrl, getSeasonsByMediaId, listMedia } from '../../services/pocketbaseService';
import { toast } from 'react-toastify';
import { FaEdit, FaTrash, FaPlus } from 'react-icons/fa';
import Modal from '../../components/common/Modal';
import { Navigate } from 'react-router-dom';

const AdminSeasonsPage = () => {
  const { mediaId: urlMediaId } = useParams();
  const navigate = useNavigate();
  const { user, userProfile, loading: authLoading } = useAuth();
  const [seasons, setSeasons] = useState([]);
  const [mediaList, setMediaList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingSeason, setEditingSeason] = useState(null);
    const [formData, setFormData] = useState({
        title: '',
        overview: '',
    release_date: '',
    season_number: '',
        is_published: false,
    media_id: urlMediaId || '',
    poster: null
    });

  const [currentPosterUrl, setCurrentPosterUrl] = useState(null);
  const [deleteExistingPoster, setDeleteExistingPoster] = useState(false);

    useEffect(() => {
    if (!user || userProfile?.role !== 'admin') {
      navigate('/admin');
      return;
    }
    loadMediaList();
    if (urlMediaId) {
      loadSeasons();
    }
  }, [user, userProfile, urlMediaId, navigate]);

  const loadMediaList = async () => {
    try {
      setLoading(true);
      const [tvData, animeData] = await Promise.all([
        listMedia('tv', 1, 100, user, false, null),
        listMedia('anime', 1, 100, user, false, null)
      ]);
      
      const combinedMedia = [
        ...(tvData.data || []),
        ...(animeData.data || [])
      ];
      
      setMediaList(combinedMedia);
      setError(null);
    } catch (err) {
      console.error('Error loading media list:', err);
      setError('Не удалось загрузить список медиа');
      toast.error('Не удалось загрузить список медиа');
    } finally {
      setLoading(false);
        }
  };

  const loadSeasons = async () => {
    try {
      setLoading(true);
      const data = await getSeasonsByMediaId(urlMediaId, {
        expand: 'media_id'
      });
      setSeasons(Array.isArray(data) ? data : []);
      setError(null);
    } catch (err) {
      console.error('Error loading seasons:', err);
      setError('Не удалось загрузить сезоны');
      toast.error('Не удалось загрузить сезоны');
    } finally {
      setLoading(false);
    }
    };

    const handleFileChange = (e) => {
    const file = e.target.files[0];
        if (file) {
      setFormData({ ...formData, poster: file });
            setDeleteExistingPoster(false);
        }
    };

    const handleRemoveExistingPoster = () => {
    setCurrentPosterUrl(null);
    setDeleteExistingPoster(true);
    setFormData({ ...formData, poster: null });
  };

  const handleOpenModal = (season = null) => {
    if (season) {
      setEditingSeason(season);
      setFormData({
        title: season.title || '',
        overview: season.overview || '',
        release_date: season.release_date || '',
        season_number: season.season_number || '',
        is_published: season.is_published || false,
        media_id: season.media_id || urlMediaId || '',
        poster: null
      });
      if (season.poster) {
        setCurrentPosterUrl(getFileUrl(season, 'poster'));
      } else {
        setCurrentPosterUrl(null);
      }
    } else {
      setEditingSeason(null);
      setFormData({
        title: '',
        overview: '',
        release_date: '',
        season_number: '',
        is_published: false,
        media_id: urlMediaId || '',
        poster: null
      });
      setCurrentPosterUrl(null);
    }
    setDeleteExistingPoster(false);
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setEditingSeason(null);
    setFormData({
      title: '',
      overview: '',
      release_date: '',
      season_number: '',
      is_published: false,
      media_id: urlMediaId || '',
      poster: null
    });
    setCurrentPosterUrl(null);
    setDeleteExistingPoster(false);
  };

    const handleSubmit = async (e) => {
        e.preventDefault();
    try {
      if (!formData.media_id) {
        toast.error('Выберите медиа');
            return;
        }

        const dataToSend = new FormData();
      dataToSend.append('media_id', formData.media_id);
      dataToSend.append('season_number', formData.season_number);
        dataToSend.append('title', formData.title || '');
        dataToSend.append('overview', formData.overview || '');
        if (formData.release_date) {
        dataToSend.append('release_date', formData.release_date);
        }
        dataToSend.append('is_published', formData.is_published);

      if (formData.poster) {
        dataToSend.append('poster', formData.poster);
        } else if (deleteExistingPoster) {
        dataToSend.append('poster', '');
        }
      
      if (editingSeason) {
        await updateSeason(editingSeason.id, dataToSend);
        toast.success('Сезон обновлен');
      } else {
        await createSeason(dataToSend);
        toast.success('Сезон создан');
      }
      handleCloseModal();
      loadSeasons();
    } catch (err) {
      console.error('Error saving season:', err);
      toast.error('Не удалось сохранить сезон');
    }
  };

  const handleDelete = async (seasonId) => {
    if (!window.confirm('Вы уверены, что хотите удалить этот сезон?')) {
      return;
    }

    try {
      await deleteSeason(seasonId);
      toast.success('Сезон удален');
      loadSeasons();
    } catch (err) {
      console.error('Error deleting season:', err);
      toast.error('Не удалось удалить сезон');
        }
  };

  if (loading) {
    return (
      <div className="container-custom pt-8 text-campfire-light">
        <div className="flex justify-center items-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-campfire-amber"></div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container-custom pt-8 text-campfire-light">
                <div className="bg-red-500/10 border border-red-500/20 text-red-500 p-4 rounded-lg">
          {error}
        </div>
      </div>
    );
  }

  return (
    <div className="container-custom pt-8 text-campfire-light">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold">
          {urlMediaId ? 'Управление сезонами' : 'Создание сезона'}
        </h1>
        <button
          onClick={() => handleOpenModal()}
          className="flex items-center px-4 py-2 bg-campfire-amber text-campfire-dark rounded-lg hover:bg-campfire-amber/80 transition-colors"
        >
          <FaPlus className="mr-2" />
          Добавить сезон
        </button>
      </div>

      {urlMediaId ? (
        <div className="bg-campfire-darker rounded-lg overflow-hidden">
          <table className="w-full">
            <thead>
              <tr className="bg-campfire-charcoal/50">
                <th className="px-6 py-3 text-left text-xs font-medium text-campfire-light/70 uppercase tracking-wider">
                  Номер
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-campfire-light/70 uppercase tracking-wider">
                  Медиа
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-campfire-light/70 uppercase tracking-wider">
                  Название
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-campfire-light/70 uppercase tracking-wider">
                  Описание
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-campfire-light/70 uppercase tracking-wider">
                  Дата выхода
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-campfire-light/70 uppercase tracking-wider">
                  Статус
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-campfire-light/70 uppercase tracking-wider">
                  Действия
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-campfire-charcoal/30">
              {Array.isArray(seasons) && seasons.map((season) => (
                <tr key={season.id} className="hover:bg-campfire-charcoal/20">
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm font-medium text-campfire-light">
                      {season.season_number}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm font-medium text-campfire-light">
                      {season.expand?.media_id?.title || 'Не указано'}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm font-medium text-campfire-light">
                      {season.title}
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="text-sm text-campfire-light/70">
                      {season.overview}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-campfire-light/70">
                    {season.release_date ? new Date(season.release_date).toLocaleDateString() : 'Не указана'}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                      season.is_published
                        ? 'bg-green-500/20 text-green-500'
                        : 'bg-campfire-ash/20 text-campfire-ash'
                    }`}>
                      {season.is_published ? 'Опубликован' : 'Черновик'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                    <button
                      onClick={() => handleOpenModal(season)}
                      className="text-campfire-amber hover:text-campfire-light mr-4"
                      title="Редактировать сезон"
                    >
                      <FaEdit />
                    </button>
                    <button
                      onClick={() => handleDelete(season.id)}
                      className="text-red-500 hover:text-red-700"
                      title="Удалить сезон"
                    >
                      <FaTrash />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {mediaList.length === 0 ? (
            <div className="col-span-full text-center py-8 text-campfire-light">
              Нет доступных медиа для создания сезонов
            </div>
          ) : (
            mediaList.map((media) => (
              <div
                key={media.id}
                className="bg-campfire-charcoal rounded-lg overflow-hidden border border-campfire-ash/20 p-4 hover:border-campfire-amber/50 transition-colors cursor-pointer"
                onClick={() => navigate(`/admin/media/${media.id}/seasons`)}
              >
                <h3 className="text-xl font-semibold text-campfire-amber mb-2">
                  {media.title}
                </h3>
                <div className="text-sm text-campfire-light/70 mb-2">
                  <p>Рейтинг: {media.average_rating ? media.average_rating.toFixed(1) : 'N/A'}</p>
                  <p>Обзоры: {media.review_count}</p>
                </div>
                <div className="flex space-x-2">
                  <span className={`px-2 py-1 text-xs rounded-full ${
                    media.is_published
                      ? 'bg-green-500/20 text-green-500'
                      : 'bg-red-500/20 text-red-500'
                  }`}>
                    {media.is_published ? 'Опубликовано' : 'Черновик'}
                  </span>
                  {media.is_popular && (
                    <span className="px-2 py-1 text-xs rounded-full bg-campfire-amber/20 text-campfire-amber">
                      Популярное
                    </span>
                  )}
                </div>
              </div>
            ))
          )}
                </div>
            )}

      <Modal
        isOpen={isModalOpen}
        onClose={handleCloseModal}
        title={editingSeason ? 'Редактировать сезон' : 'Добавить сезон'}
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label htmlFor="media_id" className="block text-sm font-medium text-campfire-light mb-1">
              Медиа
            </label>
            <select
              id="media_id"
              value={formData.media_id}
              onChange={(e) => setFormData({ ...formData, media_id: e.target.value })}
              className="w-full p-2 bg-campfire-dark border border-campfire-ash/30 rounded-md text-campfire-light"
              required
              disabled={!!urlMediaId}
            >
              <option value="">Выберите медиа</option>
              {mediaList.map((media) => (
                <option key={media.id} value={media.id}>
                  {media.title}
                </option>
              ))}
            </select>
          </div>

            <div>
            <label htmlFor="season_number" className="block text-sm font-medium text-campfire-light mb-1">
              Номер сезона
                </label>
                <input
                    type="number"
                    id="season_number"
                    value={formData.season_number}
              onChange={(e) => setFormData({ ...formData, season_number: e.target.value })}
              className="w-full p-2 bg-campfire-dark border border-campfire-ash/30 rounded-md text-campfire-light"
                    required
                />
            </div>

            <div>
            <label htmlFor="title" className="block text-sm font-medium text-campfire-light mb-1">
              Название
                </label>
                <input
                    type="text"
                    id="title"
                    value={formData.title}
              onChange={(e) => setFormData({ ...formData, title: e.target.value })}
              className="w-full p-2 bg-campfire-dark border border-campfire-ash/30 rounded-md text-campfire-light"
                />
            </div>

            <div>
            <label htmlFor="overview" className="block text-sm font-medium text-campfire-light mb-1">
              Описание
                </label>
                <textarea
                    id="overview"
                    value={formData.overview}
              onChange={(e) => setFormData({ ...formData, overview: e.target.value })}
              className="w-full p-2 bg-campfire-dark border border-campfire-ash/30 rounded-md text-campfire-light"
              rows="3"
                />
            </div>

            <div>
            <label htmlFor="release_date" className="block text-sm font-medium text-campfire-light mb-1">
              Дата выхода
                </label>
            <input
              type="date"
                    id="release_date"
              value={formData.release_date}
              onChange={(e) => setFormData({ ...formData, release_date: e.target.value })}
              className="w-full p-2 bg-campfire-dark border border-campfire-ash/30 rounded-md text-campfire-light"
                 />
            </div>

          <div>
            <label className="flex items-center space-x-2">
              <input
                type="checkbox"
                checked={formData.is_published}
                onChange={(e) => setFormData({ ...formData, is_published: e.target.checked })}
                className="rounded border-campfire-ash/30 text-campfire-amber focus:ring-campfire-amber"
              />
              <span className="text-sm text-campfire-light">Опубликовать</span>
            </label>
          </div>

            <div>
            <label htmlFor="poster" className="block text-sm font-medium text-campfire-light mb-1">
              Постер сезона
                </label>
                {currentPosterUrl && !deleteExistingPoster && (
                    <div className="mb-4">
                        <p className="text-sm text-campfire-ash mb-2">Текущий постер:</p>
                        <img src={currentPosterUrl} alt="Current Poster" className="w-24 h-auto rounded-md mb-2" />
                        <button
                            type="button"
                            onClick={handleRemoveExistingPoster}
                            className="text-red-500 hover:underline text-sm"
                        >
                            Удалить текущий постер
                        </button>
                    </div>
                )}
                <input
                    type="file"
                    id="poster"
                    name="poster"
                    onChange={handleFileChange}
                    className="w-full text-campfire-light text-sm
                       file:mr-4 file:py-2 file:px-4
                       file:rounded-md file:border-0
                       file:text-sm file:font-semibold
                       file:bg-campfire-amber file:text-campfire-dark
                       hover:file:bg-campfire-amber/80 cursor-pointer"
              accept="image/*"
            />
            </div>

            <div className="flex justify-end space-x-4 mt-6">
                <button
                    type="button"
              onClick={handleCloseModal}
                    className="btn-secondary"
                >
                    Отмена
                </button>
                <button
                    type="submit"
              className="btn-primary"
                >
              {editingSeason ? 'Сохранить' : 'Создать'}
                </button>
            </div>
        </form>
            </Modal>
        </div>
    );
};

export default AdminSeasonsPage;
