'use client';

import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { User, MapPin, Tag, CheckCircle2, Search, BrainCircuit, ArrowRight, Target, BarChart3, Factory } from 'lucide-react';
import { CardShell } from '../shared/CardShell';

const AGENTS = [
    { id: 1, name: 'Amit Verma', role: 'Sales Exec', region: 'Gujarat', score: 45, color: 'blue' },
    { id: 2, name: 'Priya Sharma', role: 'Senior Rep', region: 'Maharashtra', score: 98, color: 'emerald' }, // Winner
    { id: 3, name: 'Rahul K.', role: 'Associate', region: 'Uttar Pradesh', score: 62, color: 'purple' },
];

export const QualifyVisual = () => {
    const [status, setStatus] = useState<'idle' | 'scanning' | 'matching' | 'assigned'>('idle');

    // Animation Loop
    useEffect(() => {
        const loop = async () => {
            setStatus('idle');
            await new Promise(r => setTimeout(r, 1000));

            setStatus('scanning');
            await new Promise(r => setTimeout(r, 2000));

            setStatus('matching');
            await new Promise(r => setTimeout(r, 2000));

            setStatus('assigned');
            await new Promise(r => setTimeout(r, 3000));

            loop();
        };
        loop();
    }, []);

    return (
        <CardShell>
            <div className="h-[600px] relative bg-slate-50 dark:bg-slate-900 overflow-hidden flex flex-col items-center justify-between py-8 font-sans">

                {/* --- Background Grid --- */}
                <div className="absolute inset-0 opacity-[0.03]"
                    style={{ backgroundImage: 'linear-gradient(#6366f1 1px, transparent 1px), linear-gradient(90deg, #6366f1 1px, transparent 1px)', backgroundSize: '40px 40px' }} />

                {/* --- Top: Lead Card --- */}
                <div className="relative z-20 w-full max-w-sm px-4">
                    <div className="text-center mb-4">
                        <div className={`inline-flex items-center gap-2 px-3 py-1 rounded-full text-[10px] font-bold border backdrop-blur-md transition-all duration-500
                            ${status === 'assigned'
                                ? 'bg-green-500/10 border-green-500/30 text-green-600 dark:text-green-400'
                                : 'bg-indigo-500/10 border-indigo-500/30 text-indigo-600 dark:text-indigo-400'}`}>
                            {status === 'idle' && 'WAITING FOR INPUT'}
                            {status === 'scanning' && <><Search size={10} className="animate-spin" /> ANALYZING ATTRIBUTES</>}
                            {status === 'matching' && <><BrainCircuit size={10} className="animate-pulse" /> CALCULATING FIT SCORES</>}
                            {status === 'assigned' && <><CheckCircle2 size={10} /> LEAD ROUTED SUCCESSFULLY</>}
                        </div>
                    </div>

                    <motion.div
                        initial={{ y: -20, opacity: 0 }}
                        animate={{ y: 0, opacity: 1 }}
                        className="bg-white dark:bg-slate-800 rounded-2xl shadow-xl border border-slate-200 dark:border-slate-700 overflow-hidden relative"
                    >
                        {/* Scanning Laser */}
                        {status === 'scanning' && (
                            <motion.div
                                className="absolute left-0 right-0 h-0.5 bg-indigo-500 shadow-[0_0_15px_rgba(99,102,241,0.8)] z-10"
                                animate={{ top: ['0%', '100%'] }}
                                transition={{ duration: 1.5, repeat: Infinity, ease: "linear" }}
                            />
                        )}

                        <div className="p-4 border-b border-slate-100 dark:border-slate-700/50 flex justify-between items-center bg-slate-50/50 dark:bg-slate-900/50">
                            <div className="flex items-center gap-2">
                                <div className="w-2 h-2 rounded-full bg-orange-500 animate-pulse" />
                                <span className="text-xs font-bold text-slate-700 dark:text-slate-200">Lead #8049</span>
                            </div>
                            <Tag size={12} className="text-slate-400" />
                        </div>

                        <div className="p-4 space-y-3">
                            <div className="flex items-start gap-3">
                                <div className="w-10 h-10 rounded-lg bg-indigo-100 dark:bg-indigo-900/30 flex items-center justify-center shrink-0">
                                    <User size={18} className="text-indigo-600 dark:text-indigo-400" />
                                </div>
                                <div className="space-y-2 w-full">
                                    <div className="h-2 w-3/4 bg-slate-200 dark:bg-slate-700 rounded animate-pulse" />
                                    <div className="h-2 w-1/2 bg-slate-100 dark:bg-slate-800 rounded animate-pulse" />
                                </div>
                            </div>

                            <div className="flex gap-2">
                                <div className="flex items-center gap-1.5 px-2 py-1 rounded bg-slate-100 dark:bg-slate-800 text-[10px] font-bold text-slate-500">
                                    <MapPin size={10} /> Maharashtra
                                </div>
                                <div className="flex items-center gap-1.5 px-2 py-1 rounded bg-slate-100 dark:bg-slate-800 text-[10px] font-bold text-slate-500">
                                    <Target size={10} /> Electric Motors
                                </div>
                                <div className="flex items-center gap-1.5 px-2 py-1 rounded bg-slate-100 dark:bg-slate-800 text-[10px] font-bold text-slate-500">
                                    <Factory size={10} /> Industry
                                </div>
                            </div>
                        </div>
                    </motion.div>
                </div>

                {/* --- Center: Processing Brain --- */}
                <div className="flex-1 w-full relative flex items-center justify-center z-10">
                    {/* Connection Lines SVG */}
                    <svg className="absolute inset-0 w-full h-full pointer-events-none overflow-visible">
                        {/* Line to Winner (Center Agent) */}
                        {(status === 'matching' || status === 'assigned') && (
                            <motion.path
                                d="M 50% 0 L 50% 100%"
                                fill="none"
                                stroke={status === 'assigned' ? '#22c55e' : '#6366f1'}
                                strokeWidth="2"
                                strokeDasharray="6 6"
                                initial={{ pathLength: 0, opacity: 0 }}
                                animate={{ pathLength: 1, opacity: 1, strokeDashoffset: -20 }}
                                transition={{ duration: 0.5, strokeDashoffset: { duration: 0.5, repeat: Infinity, ease: "linear" } }}
                            />
                        )}
                    </svg>

                    <motion.div
                        animate={{
                            scale: status === 'matching' ? [1, 1.1, 1] : 1,
                            rotate: status === 'scanning' ? 360 : 0,
                            borderColor: status === 'assigned' ? '#22c55e' : '#e2e8f0'
                        }}
                        transition={{ rotate: { duration: 2, repeat: Infinity, ease: "linear" } }}
                        className={`
                            w-16 h-16 rounded-full bg-white dark:bg-slate-900 border-4 shadow-2xl z-20 flex items-center justify-center
                            ${status === 'assigned' ? 'border-green-500 text-green-500' : 'border-slate-200 dark:border-slate-700 text-indigo-500'}
                        `}
                    >
                        {status === 'assigned' ? <CheckCircle2 size={28} /> : <BrainCircuit size={28} />}
                    </motion.div>
                </div>

                {/* --- Bottom: Agents Grid --- */}
                <div className="w-full px-4 relative z-20">
                    <div className="grid grid-cols-3 gap-3">
                        {AGENTS.map((agent, i) => {
                            const isWinner = i === 1;
                            const isDimmed = status === 'assigned' && !isWinner;

                            return (
                                <motion.div
                                    key={agent.id}
                                    animate={{
                                        y: isWinner && status === 'assigned' ? -10 : 0,
                                        opacity: isDimmed ? 0.3 : 1,
                                        scale: isWinner && status === 'assigned' ? 1.05 : 1
                                    }}
                                    className={`
                                        relative p-3 rounded-xl border flex flex-col items-center gap-2 text-center transition-all duration-300
                                        ${isWinner && status === 'assigned'
                                            ? 'bg-green-50 dark:bg-green-900/20 border-green-500 dark:border-green-500 shadow-lg shadow-green-500/20'
                                            : 'bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700'}
                                    `}
                                >
                                    {/* Score Bubble */}
                                    {(status === 'matching' || status === 'assigned') && (
                                        <motion.div
                                            initial={{ scale: 0 }}
                                            animate={{ scale: 1 }}
                                            className={`absolute -top-2 right-2 text-[9px] font-bold px-1.5 py-0.5 rounded-full border
                                                ${isWinner ? 'bg-green-500 text-white border-green-600' : 'bg-slate-100 text-slate-500 border-slate-200'}
                                            `}
                                        >
                                            {status === 'assigned' ? `${agent.score}% Match` : '...'}
                                        </motion.div>
                                    )}

                                    <div className={`
                                        w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold
                                        ${isWinner && status === 'assigned' ? 'bg-green-500 text-white' : 'bg-slate-100 dark:bg-slate-700 text-slate-500'}
                                    `}>
                                        {agent.name.charAt(0)}
                                    </div>

                                    <div>
                                        <div className="text-xs font-bold text-slate-800 dark:text-slate-200 truncate w-full">{agent.name}</div>
                                        <div className="text-[10px] text-slate-400">{agent.region}</div>
                                    </div>
                                </motion.div>
                            )
                        })}
                    </div>
                </div>

            </div>
        </CardShell>
    );
};