import { Html, TransformControls } from '@react-three/drei';
import { useEffect, useRef, useState } from 'react'
import { usePlayButtonStore } from '../../../../../store/usePlayButtonStore';
import { detectModifierKeys } from '../../../../../utils/shortcutkeys/detectModifierKeys';
import CommentThreads from '../../../../../components/ui/collaboration/CommentThreads';

function CommentInstance({ comment }: { comment: CommentSchema }) {
    const { isPlaying } = usePlayButtonStore();
    const CommentRef = useRef(null);
    const [selectedComment, setSelectedComment] = useState<CommentSchema | null>(null);
    const [transformMode, setTransformMode] = useState<"translate" | "rotate" | null>(null);

    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            const keyCombination = detectModifierKeys(e);
            if (!selectedComment) return;
            if (keyCombination === "G") {
                setTransformMode((prev) => (prev === "translate" ? null : "translate"));
            }
            if (keyCombination === "R") {
                setTransformMode((prev) => (prev === "rotate" ? null : "rotate"));
            }
        };

        window.addEventListener("keydown", handleKeyDown);
        return () => window.removeEventListener("keydown", handleKeyDown);
    }, [selectedComment]);

    const commentClicked = () => {
        console.log('hii');
        setSelectedComment(comment);
    }

    if (comment.state === 'inactive' || isPlaying) return null;

    return (

        <>
            <Html
                ref={CommentRef}
                zIndexRange={[1, 0]}
                prepend
                sprite
                center
                position={comment.position}
                rotation={comment.rotation}
                className='comments-main-wrapper'
            >
                <CommentThreads commentClicked={commentClicked} />
            </Html>
            {CommentRef.current && transformMode && (
                <TransformControls
                    object={CommentRef.current}
                    mode={transformMode}
                    onMouseUp={(e) => {

                    }}
                />
            )}
        </>
    )
}

export default CommentInstance;