import {useAuth} from "../contexts/AuthContext.jsx";
import {useRef, useState} from "react";


export default function Comment({ comment, index, videoId, refetchVideo, doShowCommands=true }) {

    let {user, isAuthenticated} = useAuth();
    let commentRef = useRef();
    let [editMode, setEditMode] = useState(false);

    let editClass = "glassmorphism rounded-md p-4 mb-3 text-white focus:outline-none";

    const handleEdit = () => {
        setEditMode(true);
        const commentElement = commentRef.current;
        commentElement.contentEditable = true;
    }

    const handleDelete = async (id) => {
        try {
            const token = localStorage.getItem('token');
            const response = await fetch(`/api/comments/${id}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                }
            });

            if (response.ok) {
                // Refresh the video data to update the comments list
                refetchVideo();
            }
        } catch (error) {
            console.error('Error deleting comment:', error);
        }
    }

    const handleEditSubmit = async (id, content) => {
        if (!content.trim()) {
            alert("Comment cannot be empty");
            return;
        }

        try {
            // Retrieve the token from localStorage
            const token = localStorage.getItem('token');

            if (!token) {
                navigation('/login');
                return;
            }

            const response = await fetch(`/api/comments/${comment.id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    content: content,
                    video: videoId
                })
            });

            if (!response.ok) {
                throw new Error('Failed to post comment');
            }
            setEditMode(false);

        } catch (error) {
            console.error('Error posting comment:', error);
        }
    }

    return (
        <div key={index} className="glassmorphism rounded-md p-4 mb-3">
            <div className="flex items-center mb-2">
                <img
                    src={comment.picture || "https://placehold.co/48"}
                    alt={comment.username}
                    className="w-8 h-8 rounded-full object-cover mr-3"
                />
                <span className="font-montserrat font-bold text-white">{comment.username}</span>
                <span className="text-gray-400 ml-2 text-sm">{new Date(comment.created_at).toLocaleDateString()}</span>
            </div>
            <p className={(editMode) ? editClass : "text-white focus:outline-none "} ref={commentRef}>{comment.content}</p>
            {
                doShowCommands && (
                    <div className="flex gap-2 items-center mt-2">
                        { isAuthenticated && user.username === comment.username && editMode === false ? (
                            <button className="text-blue-500 mt-2 hover:underline" onClick={() => handleEdit(comment.id)}>
                                Modifier
                            </button>
                        ) : null }
                        { isAuthenticated && user.username === comment.username && editMode === false ? (

                            <button className="text-red-500 mt-2 hover:underline" onClick={() => handleDelete(comment.id)}>
                                Supprimer
                            </button>
                        ) : null
                        }
                        { isAuthenticated && user.username === comment.username && editMode ? (
                            <button className="text-green-500 mt-2 hover:underline" onClick={() => {
                                setEditMode(false);
                                commentRef.current.contentEditable = false;
                                handleEditSubmit(comment.id, commentRef.current.textContent);
                            }}>
                                Enregistrer
                            </button>
                        ) : null }
                        { isAuthenticated && user.username === comment.username && editMode ? (
                            <button className="text-gray-500 mt-2 hover:underline" onClick={() => {
                                setEditMode(false);
                                commentRef.current.contentEditable = false;
                            }}>
                                Annuler
                            </button>
                        ) : null }
                    </div>
                )
            }
        </div>
    )

}