import React, { useState, useEffect } from 'react';
import { FaComment, FaReply } from 'react-icons/fa';
import { pb } from '../../services/pocketbaseService';
import { createReviewCommentNotification, createCommentReplyNotification } from '../../services/notificationService';

const CommentSection = ({ reviewId }) => {
    const [comments, setComments] = useState([]);
    const [newComment, setNewComment] = useState('');
    const [replyTo, setReplyTo] = useState(null);
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
        loadComments();
    }, [reviewId]);

    const loadComments = async () => {
        try {
            const records = await pb.collection('review_comments').getList(1, 50, {
                filter: `review_id = "${reviewId}"`,
                sort: '-created',
                expand: 'user_id,parent_id'
            });
            setComments(records.items);
        } catch (error) {
            console.error('Error loading comments:', error);
        }
    };

    const handleSubmitComment = async (e) => {
        e.preventDefault();
        if (!newComment.trim() || isLoading) return;

        setIsLoading(true);
        try {
            const authData = pb.authStore.model;
            if (!authData) {
                throw new Error('Требуется авторизация');
            }

            // Получаем рецензию для уведомления
            const review = await pb.collection('reviews').getOne(reviewId, {
                expand: 'media_id'
            });

            const commentData = {
                review_id: reviewId,
                user_id: authData.id,
                content: newComment.trim(),
                parent_id: replyTo?.id || null
            };

            const comment = await pb.collection('review_comments').create(commentData);

            // Создаем уведомление
            if (replyTo) {
                // Уведомление о ответе на комментарий
                await createCommentReplyNotification(
                    replyTo.user_id,
                    replyTo,
                    comment,
                    authData
                );
            } else {
                // Уведомление о новом комментарии к рецензии
                await createReviewCommentNotification(
                    review.user_id,
                    review,
                    comment,
                    authData
                );
            }

            setNewComment('');
            setReplyTo(null);
            await loadComments();
        } catch (error) {
            console.error('Error submitting comment:', error);
        } finally {
            setIsLoading(false);
        }
    };

    const renderComment = (comment) => {
        const user = comment.expand?.user_id;
        const isReply = comment.parent_id;

        return (
            <div key={comment.id} className={`mt-4 ${isReply ? 'ml-8' : ''}`}>
                <div className="flex items-start space-x-2">
                    <img
                        src={user?.avatar || '/default-avatar.png'}
                        alt={user?.username}
                        className="w-8 h-8 rounded-full"
                    />
                    <div className="flex-1">
                        <div className="bg-gray-100 rounded-lg p-3">
                            <div className="font-medium">{user?.username}</div>
                            <p className="text-gray-700">{comment.content}</p>
                        </div>
                        <div className="mt-1 text-sm text-gray-500">
                            <button
                                onClick={() => setReplyTo(comment)}
                                className="hover:text-blue-500"
                            >
                                <FaReply className="inline mr-1" />
                                Ответить
                            </button>
                        </div>
                    </div>
                </div>
                {comment.expand?.parent_id && (
                    <div className="mt-2 text-sm text-gray-500">
                        Ответ на комментарий {comment.expand.parent_id.user_id.username}
                    </div>
                )}
            </div>
        );
    };

    return (
        <div className="mt-6">
            <h3 className="text-lg font-medium mb-4">
                <FaComment className="inline mr-2" />
                Комментарии
            </h3>

            <form onSubmit={handleSubmitComment} className="mb-6">
                <div className="flex space-x-2">
                    <input
                        type="text"
                        value={newComment}
                        onChange={(e) => setNewComment(e.target.value)}
                        placeholder={replyTo ? `Ответить ${replyTo.expand?.user_id.username}` : 'Написать комментарий...'}
                        className="flex-1 rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                    <button
                        type="submit"
                        disabled={isLoading}
                        className="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                        {isLoading ? 'Отправка...' : 'Отправить'}
                    </button>
                </div>
                {replyTo && (
                    <div className="mt-2 text-sm text-gray-500">
                        Ответ на комментарий {replyTo.expand?.user_id.username}
                        <button
                            onClick={() => setReplyTo(null)}
                            className="ml-2 text-red-500 hover:text-red-600"
                        >
                            Отменить
                        </button>
                    </div>
                )}
            </form>

            <div className="space-y-4">
                {comments.map(renderComment)}
            </div>
        </div>
    );
};

export default CommentSection; 