import React, { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { getMediaByPath, getReviewsByMediaId, getFileUrl, likeReview, unlikeReview } from '../../services/pocketbaseService';
import { FaStar, FaHeart, FaRegHeart, FaComment, FaShare, FaArrowLeft } from 'react-icons/fa';
import MobileReviewForm from '../components/MobileReviewForm';

const MobileMedia = () => {
  const { path } = useParams();
  const { userProfile } = useAuth();
  const [media, setMedia] = useState(null);
  const [reviews, setReviews] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showReviewForm, setShowReviewForm] = useState(false);
  const [activeTab, setActiveTab] = useState('reviews');

  useEffect(() => {
    window.scrollTo(0, 0);
    fetchData();
  }, [path]);

  const fetchData = async () => {
    try {
      setLoading(true);
      setError(null);

      const [mediaData, reviewsData] = await Promise.all([
        getMediaByPath(path),
        getReviewsByMediaId(path)
      ]);

      setMedia(mediaData);
      setReviews(reviewsData);
    } catch (err) {
      console.error('Error fetching media data:', err);
      setError('Не удалось загрузить данные медиа.');
    } finally {
      setLoading(false);
    }
  };

  const handleLike = async (reviewId) => {
    if (!userProfile) return;

    try {
      const review = reviews.find(r => r.id === reviewId);
      if (review.likes?.includes(userProfile.id)) {
        await unlikeReview(reviewId);
        review.likes = review.likes.filter(id => id !== userProfile.id);
      } else {
        await likeReview(reviewId);
        review.likes = [...(review.likes || []), userProfile.id];
      }
      setReviews([...reviews]);
    } catch (err) {
      console.error('Error handling like:', err);
    }
  };

  const handleShare = async () => {
    try {
      await navigator.share({
        title: media.title,
        text: `Посмотрите ${media.title} на Campfire Critics!`,
        url: window.location.href
      });
    } catch (err) {
      console.error('Error sharing:', err);
    }
  };

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

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

  if (!media) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="bg-status-error/20 text-status-error p-4 rounded-lg text-center">
          Медиа не найдено
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-campfire-dark">
      {/* Header */}
      <div className="relative h-64">
        <img
          src={getFileUrl(media, 'banner')}
          alt={media.title}
          className="w-full h-full object-cover"
        />
        <div className="absolute inset-0 bg-gradient-to-t from-campfire-dark to-transparent" />
        <div className="absolute inset-0 flex items-end p-4">
          <div className="flex items-center space-x-4">
            <Link to="/" className="text-campfire-light hover:text-campfire-amber">
              <FaArrowLeft className="w-6 h-6" />
            </Link>
            <h1 className="text-2xl font-bold text-campfire-light">{media.title}</h1>
          </div>
        </div>
      </div>

      {/* Content */}
      <div className="px-4 py-6">
        {/* Media Info */}
        <div className="flex space-x-4 mb-6">
          <img
            src={getFileUrl(media, 'poster')}
            alt={media.title}
            className="w-24 h-36 object-cover rounded-lg"
          />
          <div className="flex-grow">
            <div className="flex items-center space-x-2 mb-2">
              <FaStar className="text-campfire-amber" />
              <span className="text-campfire-light font-semibold">
                {media.average_rating?.toFixed(1) || '0.0'}
              </span>
              <span className="text-campfire-ash">
                ({media.review_count || 0} обзоров)
              </span>
            </div>
            <p className="text-campfire-ash text-sm line-clamp-3">{media.description}</p>
          </div>
        </div>

        {/* Tabs */}
        <div className="flex space-x-2 mb-6">
          <button
            onClick={() => setActiveTab('reviews')}
            className={`flex-1 py-2 px-4 rounded-full text-sm font-medium ${
              activeTab === 'reviews'
                ? 'bg-campfire-amber text-campfire-dark'
                : 'bg-campfire-charcoal/20 text-campfire-ash'
            }`}
          >
            Рецензии
          </button>
          <button
            onClick={() => setActiveTab('about')}
            className={`flex-1 py-2 px-4 rounded-full text-sm font-medium ${
              activeTab === 'about'
                ? 'bg-campfire-amber text-campfire-dark'
                : 'bg-campfire-charcoal/20 text-campfire-ash'
            }`}
          >
            О медиа
          </button>
        </div>

        {/* Tab Content */}
        {activeTab === 'reviews' ? (
          <div className="space-y-6">
            {userProfile && (
              <button
                onClick={() => setShowReviewForm(!showReviewForm)}
                className="w-full py-3 bg-campfire-amber text-campfire-dark font-semibold rounded-xl hover:bg-campfire-amber/90"
              >
                {showReviewForm ? 'Отмена' : 'Написать рецензию'}
              </button>
            )}

            {showReviewForm && (
              <MobileReviewForm
                mediaId={media.id}
                onSuccess={() => {
                  setShowReviewForm(false);
                  fetchData();
                }}
                onCancel={() => setShowReviewForm(false)}
              />
            )}

            {reviews.map((review) => (
              <div key={review.id} className="bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-xl p-4">
                <div className="flex items-center space-x-3 mb-3">
                  <Link to={`/profile/${review.expand.user_id.login}`}>
                    <img
                      src={getFileUrl(review.expand.user_id, 'profile_picture') || 'https://via.placeholder.com/150'}
                      alt={review.expand.user_id.username}
                      className="w-10 h-10 rounded-full object-cover border border-campfire-ash/30"
                    />
                  </Link>
                  <div className="flex-grow">
                    <Link to={`/profile/${review.expand.user_id.login}`} className="text-campfire-light font-semibold hover:text-campfire-amber">
                      {review.expand.user_id.username}
                    </Link>
                    <div className="flex items-center space-x-2 text-sm">
                      <FaStar className="text-campfire-amber" />
                      <span className="text-campfire-light">{review.rating}</span>
                      <span className="text-campfire-ash">
                        {new Date(review.created).toLocaleDateString()}
                      </span>
                    </div>
                  </div>
                </div>
                <div className="text-campfire-light mb-3" dangerouslySetInnerHTML={{ __html: review.content }} />
                <div className="flex items-center space-x-4">
                  <button
                    onClick={() => handleLike(review.id)}
                    className="flex items-center space-x-1 text-campfire-ash hover:text-campfire-amber"
                  >
                    {review.likes?.includes(userProfile?.id) ? (
                      <FaHeart className="text-campfire-amber" />
                    ) : (
                      <FaRegHeart />
                    )}
                    <span>{review.likes?.length || 0}</span>
                  </button>
                  <button className="flex items-center space-x-1 text-campfire-ash hover:text-campfire-amber">
                    <FaComment />
                    <span>{review.comments?.length || 0}</span>
                  </button>
                  <button
                    onClick={handleShare}
                    className="flex items-center space-x-1 text-campfire-ash hover:text-campfire-amber"
                  >
                    <FaShare />
                  </button>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="space-y-4">
            <div className="bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-xl p-4">
              <h3 className="text-campfire-light font-semibold mb-2">Описание</h3>
              <p className="text-campfire-ash">{media.description}</p>
            </div>
            {media.genres && (
              <div className="bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-xl p-4">
                <h3 className="text-campfire-light font-semibold mb-2">Жанры</h3>
                <div className="flex flex-wrap gap-2">
                  {media.genres.map((genre) => (
                    <span
                      key={genre}
                      className="px-3 py-1 bg-campfire-amber/20 text-campfire-amber rounded-full text-sm"
                    >
                      {genre}
                    </span>
                  ))}
                </div>
              </div>
            )}
            {media.release_date && (
              <div className="bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-xl p-4">
                <h3 className="text-campfire-light font-semibold mb-2">Дата выхода</h3>
                <p className="text-campfire-ash">
                  {new Date(media.release_date).toLocaleDateString()}
                </p>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default MobileMedia; 