import React, { useState, useEffect } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { pb } from '../../services/pocketbaseService';
import { getFileUrl } from '../../services/pocketbaseService';
import { useAuth } from '../../contexts/AuthContext';
import { FaArrowLeft, FaStar, FaHeart, FaComment, FaEdit, FaTrash } from 'react-icons/fa';
import { formatDistanceToNow } from 'date-fns';
import { ru } from 'date-fns/locale';

const MobileReview = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { user } = useAuth();
  const [review, setReview] = useState(null);
  const [comments, setComments] = useState([]);
  const [newComment, setNewComment] = useState('');
  const [loading, setLoading] = useState(true);
  const [liked, setLiked] = useState(false);

  useEffect(() => {
    fetchReview();
  }, [id]);

  const fetchReview = async () => {
    try {
      const record = await pb.collection('reviews').getOne(id, {
        expand: 'user_id,media_id'
      });
      setReview(record);

      // Получаем комментарии отдельно
      const comments = await pb.collection('comments').getList(1, 50, {
        filter: `review_id = "${id}"`,
        expand: 'user_id',
        sort: '-created'
      });
      setComments(comments.items);

      if (user) {
        const likes = await pb.collection('likes').getList(1, 1, {
          filter: `review_id = "${id}" && user_id = "${user.id}"`
        });
        setLiked(likes.items.length > 0);
      }
    } catch (error) {
      console.error('Error fetching review:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleLike = async () => {
    if (!user) {
      navigate('/auth/login');
      return;
    }

    try {
      if (liked) {
        const likes = await pb.collection('likes').getList(1, 1, {
          filter: `review_id = "${id}" && user_id = "${user.id}"`
        });
        if (likes.items.length > 0) {
          await pb.collection('likes').delete(likes.items[0].id);
        }
      } else {
        await pb.collection('likes').create({
          review_id: id,
          user_id: user.id
        });
      }
      setLiked(!liked);
      fetchReview();
    } catch (error) {
      console.error('Error toggling like:', error);
    }
  };

  const handleComment = async (e) => {
    e.preventDefault();
    if (!user) {
      navigate('/auth/login');
      return;
    }

    try {
      await pb.collection('comments').create({
        review_id: id,
        user_id: user.id,
        content: newComment
      });
      setNewComment('');
      fetchReview();
    } catch (error) {
      console.error('Error adding comment:', error);
    }
  };

  const handleDelete = async () => {
    if (window.confirm('Вы уверены, что хотите удалить этот обзор?')) {
      try {
        await pb.collection('reviews').delete(id);
        navigate(-1);
      } catch (error) {
        console.error('Error deleting review:', error);
      }
    }
  };

  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 (!review) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen px-4 text-center">
        <h1 className="text-2xl font-bold text-campfire-amber mb-4">Обзор не найден</h1>
        <Link
          to="/"
          className="px-6 py-3 bg-campfire-amber text-campfire-dark rounded-lg font-semibold hover:bg-campfire-amber/90 transition-colors"
        >
          Вернуться на главную
        </Link>
      </div>
    );
  }

  const isOwnReview = user && user.id === review.user_id;

  return (
    <div className="px-4 py-4">
      <button
        onClick={() => navigate(-1)}
        className="flex items-center text-campfire-light mb-6"
      >
        <FaArrowLeft className="mr-2" />
        Назад
      </button>

      <div className="bg-campfire-dark/50 border border-campfire-ash/30 rounded-lg overflow-hidden mb-6">
        <div className="relative">
          <img
            src={getFileUrl(review.expand?.media_id, 'poster')}
            alt={review.expand?.media_id?.title}
            className="w-full h-64 object-cover"
          />
          <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-campfire-dark to-transparent p-4">
            <h1 className="text-xl font-bold text-campfire-light">
              {review.expand?.media_id?.title}
            </h1>
          </div>
        </div>

        <div className="p-4">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center space-x-2">
              <img
                src={getFileUrl(review.expand?.user_id, 'profile_picture')}
                alt={review.expand?.user_id?.username}
                className="w-8 h-8 rounded-full"
              />
              <div>
                <Link
                  to={`/profile/${review.expand?.user_id?.username}`}
                  className="text-campfire-light font-semibold"
                >
                  {review.expand?.user_id?.username}
                </Link>
                <p className="text-campfire-ash text-sm">
                  {formatDistanceToNow(new Date(review.created), { addSuffix: true, locale: ru })}
                </p>
              </div>
            </div>
            {isOwnReview && (
              <div className="flex space-x-2">
                <Link
                  to={`/review/${review.id}/edit`}
                  className="p-2 text-campfire-light hover:text-campfire-amber"
                >
                  <FaEdit />
                </Link>
                <button
                  onClick={handleDelete}
                  className="p-2 text-campfire-light hover:text-red-500"
                >
                  <FaTrash />
                </button>
              </div>
            )}
          </div>

          <div className="flex items-center space-x-4 mb-4">
            <span className="text-campfire-amber">
              <FaStar className="inline mr-1" />
              {review.rating}/10
            </span>
            <button
              onClick={handleLike}
              className={`flex items-center space-x-1 ${
                liked ? 'text-red-500' : 'text-campfire-light'
              }`}
            >
              <FaHeart />
              <span>{review.likes || 0}</span>
            </button>
          </div>

          <p className="text-campfire-light whitespace-pre-wrap">
            {review.content}
          </p>
        </div>
      </div>

      <div className="space-y-4">
        <h2 className="text-lg font-semibold text-campfire-light">Комментарии</h2>

        <form onSubmit={handleComment} className="flex space-x-2">
          <input
            type="text"
            value={newComment}
            onChange={(e) => setNewComment(e.target.value)}
            placeholder="Написать комментарий..."
            className="flex-1 px-4 py-2 bg-campfire-dark/50 border border-campfire-ash/30 rounded-lg text-campfire-light focus:outline-none focus:border-campfire-amber"
          />
          <button
            type="submit"
            disabled={!newComment.trim()}
            className="px-4 py-2 bg-campfire-amber text-campfire-dark rounded-lg font-semibold hover:bg-campfire-amber/90 transition-colors disabled:opacity-50"
          >
            Отправить
          </button>
        </form>

        <div className="space-y-4">
          {comments.map((comment) => (
            <div
              key={comment.id}
              className="bg-campfire-dark/50 border border-campfire-ash/30 rounded-lg p-4"
            >
              <div className="flex items-center space-x-2 mb-2">
                <img
                  src={getFileUrl(comment.expand?.user_id, 'profile_picture')}
                  alt={comment.expand?.user_id?.username}
                  className="w-6 h-6 rounded-full"
                />
                <div>
                  <Link
                    to={`/profile/${comment.expand?.user_id?.username}`}
                    className="text-campfire-light font-semibold text-sm"
                  >
                    {comment.expand?.user_id?.username}
                  </Link>
                  <p className="text-campfire-ash text-xs">
                    {formatDistanceToNow(new Date(comment.created), { addSuffix: true, locale: ru })}
                  </p>
                </div>
              </div>
              <p className="text-campfire-light text-sm">
                {comment.content}
              </p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default MobileReview; 