import React, { useState, useRef, useEffect, useCallback } from 'react';
import { useVoice } from '../contexts/VoiceContext';
import { VideoRenderer, useParticipantTrack } from '../utils/streamUtils.jsx';
import { getUserPref, setUserPref } from '../utils/userPreferences';
import { usePlatform } from '../platform';

const MIN_WIDTH = 240;
const MIN_HEIGHT = 135;
const MAX_WIDTH_RATIO = 0.75;
const MAX_HEIGHT_RATIO = 0.75;
const DEFAULT_WIDTH = 320;
const DEFAULT_HEIGHT = 180;
const ASPECT_RATIO = 16 / 9;

const LIVE_BADGE_STYLE = {
    backgroundColor: '#ed4245', borderRadius: '4px', padding: '2px 6px',
    color: 'white', fontSize: '10px', fontWeight: 'bold',
    textTransform: 'uppercase', letterSpacing: '0.5px',
};

const FloatingStreamPiP = ({ onGoBackToStream }) => {
    const { room, watchingStreamOf, setWatchingStreamOf, voiceStates, activeChannelId } = useVoice();
    const { settings } = usePlatform();
    const pipUserId = localStorage.getItem('userId');

    const [position, setPosition] = useState(() => getUserPref(pipUserId, 'pipPosition', { x: -1, y: -1 }));
    const [size, setSize] = useState(() => getUserPref(pipUserId, 'pipSize', { width: DEFAULT_WIDTH, height: DEFAULT_HEIGHT }));
    const [hovering, setHovering] = useState(false);

    const isDragging = useRef(false);
    const isResizing = useRef(false);
    const dragOffset = useRef({ x: 0, y: 0 });
    const resizeStart = useRef({ x: 0, y: 0, width: 0, height: 0 });
    const containerRef = useRef(null);

    // Initialize position to bottom-right on mount (only if no saved position)
    useEffect(() => {
        if (position.x === -1 && position.y === -1) {
            setPosition({
                x: window.innerWidth - size.width - 24,
                y: window.innerHeight - size.height - 24,
            });
        }
    }, []);

    // Find the watched participant from the room
    const participant = (() => {
        if (!room || !watchingStreamOf) return null;
        if (room.localParticipant.identity === watchingStreamOf) return room.localParticipant;
        return room.remoteParticipants.get(watchingStreamOf) || null;
    })();

    const screenTrack = useParticipantTrack(participant, 'screenshare');

    // Resolve streamer username from voiceStates
    const streamerUsername = (() => {
        if (!watchingStreamOf) return '';
        for (const users of Object.values(voiceStates)) {
            const u = users.find(u => u.userId === watchingStreamOf);
            if (u) return u.username;
        }
        return watchingStreamOf;
    })();

    // Drag handlers
    const handleDragStart = useCallback((e) => {
        if (isResizing.current) return;
        e.preventDefault();
        isDragging.current = true;
        dragOffset.current = {
            x: e.clientX - position.x,
            y: e.clientY - position.y,
        };
    }, [position]);

    useEffect(() => {
        const handleMouseMove = (e) => {
            if (isDragging.current) {
                let newX = e.clientX - dragOffset.current.x;
                let newY = e.clientY - dragOffset.current.y;

                // Constrain to window bounds
                newX = Math.max(0, Math.min(newX, window.innerWidth - size.width));
                newY = Math.max(0, Math.min(newY, window.innerHeight - size.height));

                setPosition({ x: newX, y: newY });
            }

            if (isResizing.current) {
                const dx = e.clientX - resizeStart.current.x;
                const dy = e.clientY - resizeStart.current.y;

                // Use the larger delta to maintain aspect ratio
                const maxW = window.innerWidth * MAX_WIDTH_RATIO;
                const maxH = window.innerHeight * MAX_HEIGHT_RATIO;

                let newWidth = resizeStart.current.width + dx;
                newWidth = Math.max(MIN_WIDTH, Math.min(maxW, newWidth));
                let newHeight = newWidth / ASPECT_RATIO;

                if (newHeight > maxH) {
                    newHeight = maxH;
                    newWidth = newHeight * ASPECT_RATIO;
                }
                if (newHeight < MIN_HEIGHT) {
                    newHeight = MIN_HEIGHT;
                    newWidth = newHeight * ASPECT_RATIO;
                }

                setSize({ width: Math.round(newWidth), height: Math.round(newHeight) });
            }
        };

        const handleMouseUp = () => {
            isDragging.current = false;
            isResizing.current = false;
        };

        window.addEventListener('mousemove', handleMouseMove);
        window.addEventListener('mouseup', handleMouseUp);
        return () => {
            window.removeEventListener('mousemove', handleMouseMove);
            window.removeEventListener('mouseup', handleMouseUp);
        };
    }, [size]);

    // Resize handler
    const handleResizeStart = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        isResizing.current = true;
        resizeStart.current = {
            x: e.clientX,
            y: e.clientY,
            width: size.width,
            height: size.height,
        };
    }, [size]);

    // Debounced persist of PiP position and size
    useEffect(() => {
        if (position.x === -1 && position.y === -1) return;
        const timer = setTimeout(() => {
            setUserPref(pipUserId, 'pipPosition', position, settings);
            setUserPref(pipUserId, 'pipSize', size, settings);
        }, 300);
        return () => clearTimeout(timer);
    }, [position, size, pipUserId]);

    const handleStopWatching = useCallback(() => {
        setWatchingStreamOf(null);
    }, [setWatchingStreamOf]);

    if (!watchingStreamOf || !participant) return null;

    return (
        <div
            ref={containerRef}
            onMouseEnter={() => setHovering(true)}
            onMouseLeave={() => setHovering(false)}
            style={{
                position: 'fixed',
                left: position.x,
                top: position.y,
                width: size.width,
                height: size.height,
                zIndex: 1000,
                borderRadius: '8px',
                overflow: 'hidden',
                boxShadow: '0 8px 24px rgba(0,0,0,0.5)',
                backgroundColor: 'black',
                cursor: isDragging.current ? 'grabbing' : 'default',
                userSelect: 'none',
            }}
            onMouseDown={handleDragStart}
        >
            {/* Video content */}
            {screenTrack ? (
                <VideoRenderer track={screenTrack} style={{ objectFit: 'contain', pointerEvents: 'none' }} />
            ) : (
                <div style={{
                    width: '100%', height: '100%',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    color: '#72767d', fontSize: '13px',
                }}>
                    Loading stream...
                </div>
            )}

            {/* Hover overlay */}
            {hovering && (
                <div style={{
                    position: 'absolute', inset: 0,
                    backgroundColor: 'rgba(0,0,0,0.55)',
                    display: 'flex', flexDirection: 'column',
                    justifyContent: 'space-between',
                    padding: '8px',
                    transition: 'opacity 0.15s',
                }}>
                    {/* Top row: streamer name + back button */}
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                            <span style={{ color: 'white', fontSize: '12px', fontWeight: '600' }}>
                                {streamerUsername}
                            </span>
                            <span style={LIVE_BADGE_STYLE}>LIVE</span>
                        </div>
                        <button
                            onClick={(e) => { e.stopPropagation(); onGoBackToStream(); }}
                            title="Back to Stream"
                            style={{
                                width: '28px', height: '28px', borderRadius: '4px',
                                backgroundColor: 'rgba(255,255,255,0.15)', border: 'none',
                                color: 'white', fontSize: '16px', cursor: 'pointer',
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                transition: 'background-color 0.15s',
                            }}
                            onMouseEnter={e => e.currentTarget.style.backgroundColor = 'rgba(255,255,255,0.25)'}
                            onMouseLeave={e => e.currentTarget.style.backgroundColor = 'rgba(255,255,255,0.15)'}
                        >
                            {/* Back arrow icon */}
                            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                                <path d="M6.5 12.5L2 8L6.5 3.5M2.5 8H14" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                            </svg>
                        </button>
                    </div>

                    {/* Bottom row: stop watching */}
                    <div style={{ display: 'flex', justifyContent: 'center' }}>
                        <button
                            onClick={(e) => { e.stopPropagation(); handleStopWatching(); }}
                            style={{
                                backgroundColor: 'rgba(0,0,0,0.6)', color: 'white', border: 'none',
                                padding: '6px 14px', borderRadius: '4px', fontWeight: '600',
                                fontSize: '12px', cursor: 'pointer',
                                transition: 'background-color 0.15s',
                            }}
                            onMouseEnter={e => e.currentTarget.style.backgroundColor = 'rgba(0,0,0,0.8)'}
                            onMouseLeave={e => e.currentTarget.style.backgroundColor = 'rgba(0,0,0,0.6)'}
                        >
                            Stop Watching
                        </button>
                    </div>
                </div>
            )}

            {/* Resize handle (bottom-right corner) */}
            <div
                onMouseDown={handleResizeStart}
                style={{
                    position: 'absolute',
                    bottom: 0,
                    right: 0,
                    width: '16px',
                    height: '16px',
                    cursor: 'nwse-resize',
                    zIndex: 2,
                }}
            >
                {/* Diagonal grip lines */}
                <svg width="16" height="16" viewBox="0 0 16 16" style={{ opacity: hovering ? 0.6 : 0 , transition: 'opacity 0.15s' }}>
                    <line x1="14" y1="4" x2="4" y2="14" stroke="white" strokeWidth="1.5"/>
                    <line x1="14" y1="8" x2="8" y2="14" stroke="white" strokeWidth="1.5"/>
                    <line x1="14" y1="12" x2="12" y2="14" stroke="white" strokeWidth="1.5"/>
                </svg>
            </div>
        </div>
    );
};

export default FloatingStreamPiP;
