import React, { useState, useRef, useEffect } from 'react';
import { Camera, ChevronRight, X } from 'lucide-react';
import { comms } from '../communication';
import { useAlert } from '../contexts/AlertContext';

interface VisionMenuProps {
    isOpen: boolean;
    onClose: () => void;
}

export const VisionMenu: React.FC<VisionMenuProps> = ({ isOpen, onClose }) => {
    const [activeSubmenu, setActiveSubmenu] = useState<string | null>(null);
    const menuRef = useRef<HTMLDivElement>(null);
    const { showAlert } = useAlert();

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
                onClose();
            }
        };

        if (isOpen) {
            document.addEventListener('mousedown', handleClickOutside);
        }

        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [isOpen, onClose]);

    if (!isOpen) return null;

    const handleVisionCommand = async (commandFn: () => Promise<{ success: boolean; message: string }>, actionName: string) => {
        try {
            const result = await commandFn();
            if (result.success) {
                console.log(`[VisionMenu] ${actionName}: ${result.message}`);
            } else {
                console.error(`[VisionMenu] ${actionName} failed: ${result.message}`);
                showAlert({
                    type: 'error',
                    title: `${actionName} Failed`,
                    message: result.message
                });
            }
        } catch (error: any) {
            console.error(`[VisionMenu] ${actionName} error:`, error);
            showAlert({
                type: 'error',
                title: `${actionName} Error`,
                message: error.message || 'Unknown error'
            });
        }
    };

    return (
        <div
            ref={menuRef}
            className="absolute top-20 left-1/2 -translate-x-1/2 z-50 bg-black/95 backdrop-blur-md border border-neon-blue/50 rounded-lg shadow-glow-blue min-w-[300px]"
        >
            {/* Header */}
            <div className="flex items-center justify-between p-4 border-b border-white/10">
                <div className="flex items-center gap-3">
                    <Camera className="w-5 h-5 text-neon-blue" />
                    <h3 className="font-tech font-bold text-lg text-white">VISION</h3>
                </div>
                <button
                    onClick={onClose}
                    className="text-slate-400 hover:text-white transition-colors"
                >
                    <X className="w-5 h-5" />
                </button>
            </div>

            {/* Menu Items */}
            <div className="p-2">
                {/* Camera (QRCode) */}
                <div className="relative">
                    <button
                        onMouseEnter={() => setActiveSubmenu('qrcode')}
                        className="w-full flex items-center justify-between px-4 py-3 text-left text-slate-300 hover:bg-neon-blue/10 hover:text-neon-blue rounded transition-colors font-tech"
                    >
                        <span>Camera (QRCode)</span>
                        <ChevronRight className="w-4 h-4" />
                    </button>

                    {/* QRCode Submenu */}
                    {activeSubmenu === 'qrcode' && (
                        <div
                            className="absolute left-full top-0 ml-1 bg-black/95 backdrop-blur-md border border-neon-blue/50 rounded-lg shadow-glow-blue min-w-[200px] p-2"
                            onMouseLeave={() => setActiveSubmenu(null)}
                        >
                            <button
                                onClick={() => handleVisionCommand(() => comms.cameraConnect(), 'Camera Connect')}
                                className="w-full px-4 py-2 text-left text-slate-300 hover:bg-neon-blue/10 hover:text-neon-blue rounded transition-colors text-sm"
                            >
                                Connect
                            </button>
                            <div className="h-px bg-white/10 my-1" />
                            <button
                                onClick={() => handleVisionCommand(() => comms.cameraGetImage(), 'Camera Get Image')}
                                className="w-full px-4 py-2 text-left text-slate-300 hover:bg-neon-blue/10 hover:text-neon-blue rounded transition-colors text-sm"
                            >
                                Get Image
                            </button>
                            <button
                                onClick={() => handleVisionCommand(() => comms.cameraLiveView(), 'Camera Live View')}
                                className="w-full px-4 py-2 text-left text-slate-300 hover:bg-neon-blue/10 hover:text-neon-blue rounded transition-colors text-sm"
                            >
                                Live View
                            </button>
                            <button
                                onClick={() => handleVisionCommand(() => comms.cameraReadTest(), 'Camera Read Test')}
                                className="w-full px-4 py-2 text-left text-slate-300 hover:bg-neon-blue/10 hover:text-neon-blue rounded transition-colors text-sm"
                            >
                                Read Test
                            </button>
                        </div>
                    )}
                </div>

                {/* Barcode (Keyence) */}
                <div className="relative">
                    <button
                        onMouseEnter={() => setActiveSubmenu('keyence')}
                        className="w-full flex items-center justify-between px-4 py-3 text-left text-slate-300 hover:bg-neon-blue/10 hover:text-neon-blue rounded transition-colors font-tech"
                    >
                        <span>Barcode (Keyence)</span>
                        <ChevronRight className="w-4 h-4" />
                    </button>

                    {/* Keyence Submenu */}
                    {activeSubmenu === 'keyence' && (
                        <div
                            className="absolute left-full top-0 ml-1 bg-black/95 backdrop-blur-md border border-neon-blue/50 rounded-lg shadow-glow-blue min-w-[200px] p-2"
                            onMouseLeave={() => setActiveSubmenu(null)}
                        >
                            <button
                                onClick={() => handleVisionCommand(() => comms.keyenceGetImage(), 'Keyence Get Image')}
                                className="w-full px-4 py-2 text-left text-slate-300 hover:bg-neon-blue/10 hover:text-neon-blue rounded transition-colors text-sm"
                            >
                                Get Image
                            </button>
                            <div className="h-px bg-white/10 my-1" />
                            <button
                                onClick={() => handleVisionCommand(() => comms.keyenceTriggerOn(), 'Keyence Trigger On')}
                                className="w-full px-4 py-2 text-left text-slate-300 hover:bg-neon-blue/10 hover:text-neon-blue rounded transition-colors text-sm"
                            >
                                Trigger On
                            </button>
                            <button
                                onClick={() => handleVisionCommand(() => comms.keyenceTriggerOff(), 'Keyence Trigger Off')}
                                className="w-full px-4 py-2 text-left text-slate-300 hover:bg-neon-blue/10 hover:text-neon-blue rounded transition-colors text-sm"
                            >
                                Trigger Off
                            </button>
                            <button
                                onClick={() => handleVisionCommand(() => comms.keyenceSaveImage(), 'Keyence Save Image')}
                                className="w-full px-4 py-2 text-left text-slate-300 hover:bg-neon-blue/10 hover:text-neon-blue rounded transition-colors text-sm"
                            >
                                Save Image
                            </button>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};
