import React, { useState, useEffect, useRef } from 'react';
import { cn } from '@/lib/utils';
import { CheckCircle2 } from 'lucide-react';

interface MatchingQuestionProps {
    options: Array<{ left: string; right: string }>;
    onSubmit: (answerData: Array<{ left: string; right: string }>) => void;
    disabled?: boolean;
}

const COLORS = [
    '#f43f5e', // rose-500
    '#0ea5e9', // sky-500
    '#10b981', // emerald-500
    '#f59e0b', // amber-500
    '#0ea5e9', // sky-500
    '#ec4899', // pink-500
];

export default function MatchingQuestion({ options, onSubmit, disabled }: MatchingQuestionProps) {
    const [leftItems, setLeftItems] = useState<Array<{ id: string; text: string; originalIndex: number }>>([]);
    const [rightItems, setRightItems] = useState<Array<{ id: string; text: string; originalIndex: number }>>([]);
    
    const [pairs, setPairs] = useState<Array<{ leftId: string; rightId: string; color: string }>>([]);
    const [selectedLeft, setSelectedLeft] = useState<string | null>(null);
    const [selectedRight, setSelectedRight] = useState<string | null>(null);

    const containerRef = useRef<HTMLDivElement>(null);
    const leftRefs = useRef<Record<string, HTMLDivElement | null>>({});
    const rightRefs = useRef<Record<string, HTMLDivElement | null>>({});
    
    const [lines, setLines] = useState<Array<{ x1: number; y1: number; x2: number; y2: number; color: string; id: string }>>([]);

    useEffect(() => {
        // Initialize and shuffle items
        const lefts = options.map((opt, i) => ({ id: `L${i}`, text: opt.left, originalIndex: i }));
        const rights = options.map((opt, i) => ({ id: `R${i}`, text: opt.right, originalIndex: i }));
        
        // Shuffle right column so it's not a direct map
        const shuffledRights = [...rights].sort(() => Math.random() - 0.5);
        const shuffledLefts = [...lefts].sort(() => Math.random() - 0.5);
        
        setLeftItems(shuffledLefts);
        setRightItems(shuffledRights);
    }, [options]);

    const updateLines = () => {
        if (!containerRef.current) return;
        const containerRect = containerRef.current.getBoundingClientRect();
        
        const newLines = pairs.map(pair => {
            const leftEl = leftRefs.current[pair.leftId];
            const rightEl = rightRefs.current[pair.rightId];
            if (!leftEl || !rightEl) return null;

            const lRect = leftEl.getBoundingClientRect();
            const rRect = rightEl.getBoundingClientRect();

            // Calculate coordinates relative to the container
            const x1 = lRect.right - containerRect.left;
            const y1 = lRect.top + lRect.height / 2 - containerRect.top;
            
            const x2 = rRect.left - containerRect.left;
            const y2 = rRect.top + rRect.height / 2 - containerRect.top;

            return {
                id: `${pair.leftId}-${pair.rightId}`,
                x1, y1, x2, y2,
                color: pair.color
            };
        }).filter(Boolean) as typeof lines;
        
        setLines(newLines);
    };

    // Update lines on resize or pairs change
    useEffect(() => {
        updateLines();
        window.addEventListener('resize', updateLines);
        return () => window.removeEventListener('resize', updateLines);
    }, [pairs, leftItems, rightItems]);

    useEffect(() => {
        // Handle selection logic
        if (selectedLeft && selectedRight) {
            // Create a pair
            // Check if already paired
            const existingLeftPair = pairs.find(p => p.leftId === selectedLeft);
            const existingRightPair = pairs.find(p => p.rightId === selectedRight);
            
            let newPairs = [...pairs];
            if (existingLeftPair) newPairs = newPairs.filter(p => p.leftId !== selectedLeft);
            if (existingRightPair) newPairs = newPairs.filter(p => p.rightId !== selectedRight);
            
            newPairs.push({
                leftId: selectedLeft,
                rightId: selectedRight,
                color: COLORS[newPairs.length % COLORS.length]
            });
            
            setPairs(newPairs);
            setSelectedLeft(null);
            setSelectedRight(null);
        }
    }, [selectedLeft, selectedRight, pairs]);

    const handleLeftClick = (id: string) => {
        if (disabled) return;
        if (selectedLeft === id) {
            setSelectedLeft(null);
        } else {
            setSelectedLeft(id);
        }
    };

    const handleRightClick = (id: string) => {
        if (disabled) return;
        if (selectedRight === id) {
            setSelectedRight(null);
        } else {
            setSelectedRight(id);
        }
    };

    const removePair = (leftId: string, rightId: string) => {
        if (disabled) return;
        setPairs(pairs.filter(p => p.leftId !== leftId || p.rightId !== rightId));
    };

    const handleSubmit = () => {
        // Map pairs back to text
        const answerData = pairs.map(p => {
            const lText = leftItems.find(i => i.id === p.leftId)?.text || '';
            const rText = rightItems.find(i => i.id === p.rightId)?.text || '';
            return { left: lText, right: rText };
        });
        onSubmit(answerData);
    };

    const isAllPaired = pairs.length === options.length;

    return (
        <div className="flex flex-col gap-6">
            <div className="text-center text-slate-300 mb-2">
                Tap kotak di kiri, lalu tap kotak di kanan yang sesuai untuk menjodohkan.
            </div>

            <div className="relative flex justify-between gap-12 sm:gap-24 min-h-[300px]" ref={containerRef}>
                {/* SVG Overlay for lines */}
                <svg className="absolute top-0 left-0 w-full h-full pointer-events-none overflow-visible" style={{ zIndex: 0 }}>
                    {lines.map((line) => (
                        <line 
                            key={line.id}
                            x1={line.x1} 
                            y1={line.y1} 
                            x2={line.x2} 
                            y2={line.y2} 
                            stroke={line.color} 
                            strokeWidth="4"
                            strokeLinecap="round"
                            className="drop-shadow-lg"
                        />
                    ))}
                </svg>

                {/* Left Column */}
                <div className="flex flex-col gap-4 w-1/2 z-10 relative">
                    {leftItems.map((item) => {
                        const isSelected = selectedLeft === item.id;
                        const pair = pairs.find(p => p.leftId === item.id);
                        return (
                            <div 
                                key={item.id}
                                ref={(el) => { leftRefs.current[item.id] = el; }}
                                onClick={() => pair ? removePair(pair.leftId, pair.rightId) : handleLeftClick(item.id)}
                                className={cn(
                                    "p-4 rounded-xl text-center font-bold cursor-pointer transition-all border-2 flex items-center justify-center min-h-[60px]",
                                    isSelected ? "bg-primary-500/20 border-primary-500 scale-105" : 
                                    pair ? "bg-slate-800 border-transparent shadow-lg text-white" : 
                                    "bg-slate-700/80 border-slate-600 hover:bg-slate-600/80 hover:border-slate-500 text-slate-200",
                                    disabled && "pointer-events-none opacity-80"
                                )}
                                style={pair ? { borderColor: pair.color, backgroundColor: `${pair.color}20` } : {}}
                            >
                                {item.text}
                            </div>
                        );
                    })}
                </div>

                {/* Right Column */}
                <div className="flex flex-col gap-4 w-1/2 z-10 relative">
                    {rightItems.map((item) => {
                        const isSelected = selectedRight === item.id;
                        const pair = pairs.find(p => p.rightId === item.id);
                        return (
                            <div 
                                key={item.id}
                                ref={(el) => { rightRefs.current[item.id] = el; }}
                                onClick={() => pair ? removePair(pair.leftId, pair.rightId) : handleRightClick(item.id)}
                                className={cn(
                                    "p-4 rounded-xl text-center font-bold cursor-pointer transition-all border-2 flex items-center justify-center min-h-[60px]",
                                    isSelected ? "bg-primary-500/20 border-primary-500 scale-105" : 
                                    pair ? "bg-slate-800 border-transparent shadow-lg text-white" : 
                                    "bg-slate-700/80 border-slate-600 hover:bg-slate-600/80 hover:border-slate-500 text-slate-200",
                                    disabled && "pointer-events-none opacity-80"
                                )}
                                style={pair ? { borderColor: pair.color, backgroundColor: `${pair.color}20` } : {}}
                            >
                                {item.text}
                            </div>
                        );
                    })}
                </div>
            </div>

            {!disabled && (
                <div className="flex justify-center mt-6">
                    <button
                        onClick={handleSubmit}
                        disabled={pairs.length === 0}
                        className={cn(
                            "flex items-center gap-2 px-8 py-4 rounded-full font-bold text-lg transition-all",
                            pairs.length > 0
                                ? "bg-emerald-500 hover:bg-emerald-400 text-white shadow-lg shadow-emerald-500/30 hover:-translate-y-1" 
                                : "bg-slate-700 text-slate-400 cursor-not-allowed"
                        )}
                    >
                        <CheckCircle2 className="w-6 h-6" />
                        Kirim Jawaban
                    </button>
                </div>
            )}
        </div>
    );
}
