import { motion, AnimatePresence } from 'framer-motion';
import { X, Brain, Calendar, TrendingUp, TrendingDown, Minus } from 'lucide-react';
import type { JourneyEvent } from '@/types';

// ─── Radial Sentiment Gauge ────────────────────────────────────────────────────
function SentimentGauge({ score }: { score: number }) {
    const radius = 44;
    const stroke = 6;
    const normalizedRadius = radius - stroke / 2;
    const circumference = normalizedRadius * 2 * Math.PI;
    // Only draw 270° arc (from 135° to 405°)
    const arcLength = circumference * 0.75;
    const offset = arcLength - (score / 100) * arcLength;

    const color =
        score >= 70 ? '#22c55e' :
            score >= 40 ? '#f59e0b' : '#ef4444';

    return (
        <div className="relative flex items-center justify-center" style={{ width: 100, height: 100 }}>
            <svg width={100} height={100} style={{ transform: 'rotate(135deg)' }}>
                {/* Track */}
                <circle
                    cx={50} cy={50} r={normalizedRadius}
                    fill="none"
                    stroke="rgba(255,255,255,0.06)"
                    strokeWidth={stroke}
                    strokeDasharray={`${arcLength} ${circumference}`}
                    strokeLinecap="round"
                />
                {/* Value arc */}
                <motion.circle
                    cx={50} cy={50} r={normalizedRadius}
                    fill="none"
                    stroke={color}
                    strokeWidth={stroke}
                    strokeDasharray={`${arcLength} ${circumference}`}
                    strokeLinecap="round"
                    initial={{ strokeDashoffset: arcLength }}
                    animate={{ strokeDashoffset: offset }}
                    transition={{ duration: 0.8, ease: 'easeOut' }}
                    style={{ filter: `drop-shadow(0 0 6px ${color})` }}
                />
            </svg>
            {/* Centre label */}
            <div className="absolute inset-0 flex flex-col items-center justify-center">
                <span className="text-xl font-bold text-white leading-none">{score}</span>
                <span className="text-[9px] text-white/40 uppercase tracking-wider mt-0.5">score</span>
            </div>
        </div>
    );
}

// ─── Inspector Panel ───────────────────────────────────────────────────────────
interface InspectorPanelProps {
    event: JourneyEvent | null;
    onClose: () => void;
}

const TYPE_LABELS: Record<JourneyEvent['type'], string> = {
    call: 'Phone Call',
    visit: 'Site Visit',
    chat: 'Chat Session',
    negotiation: 'Negotiation',
};

export function InspectorPanel({ event, onClose }: InspectorPanelProps) {
    const SentimentIcon =
        event && event.sentimentScore >= 70 ? TrendingUp :
            event && event.sentimentScore >= 40 ? Minus : TrendingDown;

    const sentimentColor =
        event && event.sentimentScore >= 70 ? 'text-green-400' :
            event && event.sentimentScore >= 40 ? 'text-amber-400' : 'text-red-400';

    return (
        <AnimatePresence>
            {event && (
                <motion.div
                    key={event.id}
                    layout
                    initial={{ width: 0, opacity: 0 }}
                    animate={{ width: '30%', opacity: 1 }}
                    exit={{ width: 0, opacity: 0 }}
                    transition={{ type: 'spring', stiffness: 280, damping: 30 }}
                    className="flex-shrink-0 h-full overflow-hidden border-l border-white/5"
                    style={{
                        background: 'rgba(255,255,255,0.03)',
                        backdropFilter: 'blur(12px)',
                    }}
                >
                    <div className="h-full overflow-y-auto custom-scrollbar p-4 flex flex-col gap-4 min-w-[220px]">
                        {/* Header */}
                        <div className="flex items-start justify-between gap-2">
                            <div className="flex-1 min-w-0">
                                <p className="text-[10px] uppercase tracking-widest text-white/30 mb-1">
                                    {TYPE_LABELS[event.type]}
                                </p>
                                <h4 className="text-white font-semibold text-sm leading-tight truncate">
                                    {event.title}
                                </h4>
                                <div className="flex items-center gap-1 mt-1 text-white/40 text-[10px]">
                                    <Calendar className="w-3 h-3" />
                                    {event.timestamp}
                                </div>
                            </div>
                            <button
                                onClick={onClose}
                                className="w-7 h-7 rounded-lg bg-white/5 hover:bg-white/10 flex items-center justify-center flex-shrink-0 transition-colors"
                            >
                                <X className="w-3.5 h-3.5 text-white/50" />
                            </button>
                        </div>

                        {/* Sentiment Gauge */}
                        <div className="flex flex-col items-center gap-2 py-2">
                            <SentimentGauge score={event.sentimentScore} />
                            <div className={`flex items-center gap-1 text-xs font-medium ${sentimentColor}`}>
                                <SentimentIcon className="w-3.5 h-3.5" />
                                {event.sentimentScore >= 70 ? 'High Interest' :
                                    event.sentimentScore >= 40 ? 'Neutral' : 'Low Engagement'}
                            </div>
                        </div>

                        {/* Divider */}
                        <div className="h-px bg-white/5" />

                        {/* Summary */}
                        <div>
                            <p className="text-[10px] uppercase tracking-widest text-white/30 mb-2">Summary</p>
                            <p className="text-white/70 text-xs leading-relaxed">{event.summary}</p>
                        </div>

                        {/* AI Insight */}
                        {event.aiInsight && (
                            <div className="rounded-xl bg-blue-500/5 border border-blue-500/15 p-3">
                                <div className="flex items-center gap-1.5 mb-2">
                                    <Brain className="w-3.5 h-3.5 text-blue-400" />
                                    <span className="text-[10px] uppercase tracking-widest text-blue-400 font-semibold">
                                        AI Insight
                                    </span>
                                </div>
                                <p className="text-white/70 text-xs leading-relaxed">{event.aiInsight}</p>
                            </div>
                        )}

                        {/* Evidence placeholder */}
                        <div>
                            <p className="text-[10px] uppercase tracking-widest text-white/30 mb-2">Evidence</p>
                            <div className="rounded-xl overflow-hidden border border-white/5 bg-white/3 aspect-video flex items-center justify-center">
                                <div className="text-center">
                                    <div className="w-8 h-8 rounded-full bg-white/5 flex items-center justify-center mx-auto mb-2">
                                        <span className="text-lg">📷</span>
                                    </div>
                                    <p className="text-white/30 text-[10px]">
                                        {event.evidenceLabel ?? 'Camera snapshot'}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </motion.div>
            )}
        </AnimatePresence>
    );
}
