import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { GitBranch, ChevronRight } from 'lucide-react';
import type { JourneyClient } from '@/types';
import { RiverPath } from './RiverPath';
import { InspectorPanel } from './InspectorPanel';

// ─── Mock Data ─────────────────────────────────────────────────────────────────
const MOCK_CLIENTS: JourneyClient[] = [
    {
        id: 'c1',
        name: 'Quantum Dynamics',
        initials: 'QD',
        stage: 'Negotiation',
        overallScore: 88,
        events: [
            {
                id: 'e1', type: 'visit', timestamp: 'Feb 10, 10:30 AM',
                sentimentScore: 42, title: 'Initial Showroom Visit',
                summary: 'Client toured the main lobby and reception area. Showed moderate interest in the view from upper floors.',
                aiInsight: 'Client lingered 4 mins near the floor plan display — a strong signal of spatial curiosity.',
                evidenceLabel: 'Lobby cam · Frame 0:04:12',
            },
            {
                id: 'e2', type: 'call', timestamp: 'Feb 12, 2:00 PM',
                sentimentScore: 58, title: 'Follow-up Call',
                summary: 'Discussed pricing tiers and payment schedule. Client requested a custom ROI breakdown.',
                aiInsight: 'Vocal tone analysis indicates growing confidence. Recommend sending ROI deck within 24h.',
                evidenceLabel: 'Call recording · 18 min',
            },
            {
                id: 'e3', type: 'visit', timestamp: 'Feb 14, 11:00 AM',
                sentimentScore: 75, title: 'Unit 402 Tour',
                summary: 'Detailed walkthrough of the penthouse unit. Client spent 5 mins examining the Italian marble flooring.',
                aiInsight: 'Dwell time on premium finishes was 3× the average. High purchase intent signal.',
                evidenceLabel: 'Unit 402 cam · Frame 0:05:44',
            },
            {
                id: 'e4', type: 'negotiation', timestamp: 'Feb 17, 4:00 PM',
                sentimentScore: 91, title: 'Contract Review',
                summary: 'Legal team reviewed terms. Minor pushback on payment timeline. Positive overall tone.',
                aiInsight: 'Sentiment peaked during the amenities discussion. Close probability: 87%.',
                evidenceLabel: 'Meeting room cam · Frame 0:22:10',
            },
        ],
    },
    {
        id: 'c2',
        name: 'Nebula Ventures',
        initials: 'NV',
        stage: 'Discovery',
        overallScore: 45,
        events: [
            {
                id: 'e5', type: 'chat', timestamp: 'Feb 15, 9:00 AM',
                sentimentScore: 35, title: 'WhatsApp Inquiry',
                summary: 'Client asked about availability and pricing for 2BR units. Seemed price-sensitive.',
                aiInsight: 'Short message length and delayed replies suggest low urgency. Nurture with value content.',
                evidenceLabel: 'Chat log · 6 messages',
            },
            {
                id: 'e6', type: 'visit', timestamp: 'Feb 16, 3:00 PM',
                sentimentScore: 52, title: 'Showroom Walk-in',
                summary: 'Unscheduled visit. Toured the 2BR model unit. Hesitated at the pricing board.',
                aiInsight: 'Micro-expressions detected: confusion near pricing. Suggest a tailored payment plan.',
                evidenceLabel: 'Showroom cam · Frame 0:08:30',
            },
        ],
    },
    {
        id: 'c3',
        name: 'Apex Industries',
        initials: 'AI',
        stage: 'Proposal',
        overallScore: 68,
        events: [
            {
                id: 'e7', type: 'call', timestamp: 'Feb 13, 10:00 AM',
                sentimentScore: 60, title: 'Discovery Call',
                summary: 'Initial qualification call. Client interested in bulk purchase for corporate housing.',
                aiInsight: 'High-value opportunity. Bulk discount framing will accelerate decision.',
                evidenceLabel: 'Call recording · 25 min',
            },
            {
                id: 'e8', type: 'visit', timestamp: 'Feb 15, 2:00 PM',
                sentimentScore: 78, title: 'Corporate Tour',
                summary: 'Toured 3 units simultaneously with their facilities manager. Strong engagement.',
                aiInsight: 'Facilities manager asked about smart home integration — a key buying signal.',
                evidenceLabel: 'Floor 7 cam · Frame 0:12:05',
            },
            {
                id: 'e9', type: 'negotiation', timestamp: 'Feb 18, 11:00 AM',
                sentimentScore: 65, title: 'Proposal Presentation',
                summary: 'Presented bulk pricing proposal. Legal team raised concerns about contract clauses.',
                aiInsight: 'Blocker identified: legal review. Recommend offering a compliance workshop.',
                evidenceLabel: 'Boardroom cam · Frame 0:31:20',
            },
        ],
    },
];

// ─── Client Card (Left Roster) ─────────────────────────────────────────────────
function ClientCard({
    client,
    isActive,
    onClick,
}: {
    client: JourneyClient;
    isActive: boolean;
    onClick: () => void;
}) {
    const scoreColor =
        client.overallScore >= 70 ? 'text-green-400' :
            client.overallScore >= 40 ? 'text-amber-400' : 'text-red-400';

    return (
        <motion.button
            onClick={onClick}
            whileHover={{ x: 2 }}
            className={`w-full text-left p-3 rounded-xl border transition-all relative overflow-hidden ${isActive
                ? 'bg-blue-500/10 border-blue-500/30'
                : 'bg-white/3 border-white/5 hover:bg-white/6 hover:border-white/10'
                }`}
        >
            {isActive && (
                <motion.div
                    layoutId="activeClientGlow"
                    className="absolute inset-0 bg-blue-500/5 rounded-xl pointer-events-none"
                    style={{ boxShadow: 'inset 0 0 20px rgba(59,130,246,0.1)' }}
                />
            )}
            <div className="relative flex items-center gap-2.5">
                {/* Avatar */}
                <div className={`w-9 h-9 rounded-lg flex items-center justify-center text-xs font-bold flex-shrink-0 ${isActive ? 'bg-blue-500/20 text-blue-300' : 'bg-white/8 text-white/60'
                    }`}>
                    {client.initials}
                </div>
                <div className="flex-1 min-w-0">
                    <p className="text-white text-xs font-medium truncate">{client.name}</p>
                    <p className="text-white/40 text-[10px] truncate">{client.stage}</p>
                </div>
                <div className="flex flex-col items-end gap-1">
                    <span className={`text-xs font-bold ${scoreColor}`}>{client.overallScore}</span>
                    {isActive && <ChevronRight className="w-3 h-3 text-blue-400" />}
                </div>
            </div>
            {/* Score bar */}
            <div className="mt-2 h-0.5 rounded-full bg-white/5 overflow-hidden">
                <motion.div
                    className={`h-full rounded-full ${client.overallScore >= 70 ? 'bg-green-400' :
                        client.overallScore >= 40 ? 'bg-amber-400' : 'bg-red-400'
                        }`}
                    initial={{ width: 0 }}
                    animate={{ width: `${client.overallScore}%` }}
                    transition={{ duration: 0.6, ease: 'easeOut' }}
                />
            </div>
        </motion.button>
    );
}

// ─── Main JourneyRiver Component ───────────────────────────────────────────────
export function JourneyRiver() {
    const [activeClientId, setActiveClientId] = useState<string>(MOCK_CLIENTS[0].id);
    const [selectedEventId, setSelectedEventId] = useState<string | null>(null);

    const activeClient = MOCK_CLIENTS.find(c => c.id === activeClientId) ?? MOCK_CLIENTS[0];
    const selectedEvent = activeClient.events.find(e => e.id === selectedEventId) ?? null;

    const handleSelectClient = (id: string) => {
        setActiveClientId(id);
        setSelectedEventId(null);
    };

    return (
        <motion.div
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5, delay: 0.3 }}
            className="relative w-full h-full rounded-2xl overflow-hidden flex"
            style={{
                background: 'rgba(8, 10, 18, 0.82)',
                border: '1px solid rgba(59,130,246,0.14)',
                backdropFilter: 'blur(24px)',
                WebkitBackdropFilter: 'blur(24px)',
                boxShadow: '0 0 0 1px rgba(255,255,255,0.04), 0 4px 32px rgba(0,0,0,0.55), 0 0 60px rgba(59,130,246,0.06)',
            }}
        >
            {/* ── Left Panel: Roster (20%) ─────────────────────────────────────── */}
            <div
                className="flex-shrink-0 flex flex-col border-r border-white/5"
                style={{ width: '22%' }}
            >
                {/* Header */}
                <div className="p-3 border-b border-white/5 flex-shrink-0">
                    <div className="flex items-center gap-2">
                        <div className="w-8 h-8 rounded-xl bg-blue-500/20 flex items-center justify-center">
                            <GitBranch className="w-3.5 h-3.5 text-blue-400" />
                        </div>
                        <div>
                            <h3 className="text-white text-sm font-medium">Journey River</h3>
                            <p className="text-white/40 text-[10px]">{MOCK_CLIENTS.length} clients tracked</p>
                        </div>
                    </div>
                </div>

                {/* Client list */}
                <div className="flex-1 overflow-y-auto custom-scrollbar p-2 space-y-1.5">
                    {MOCK_CLIENTS.map(client => (
                        <ClientCard
                            key={client.id}
                            client={client}
                            isActive={client.id === activeClientId}
                            onClick={() => handleSelectClient(client.id)}
                        />
                    ))}
                </div>

                {/* Footer legend */}
                <div className="p-3 border-t border-white/5 flex-shrink-0">
                    <p className="text-[9px] text-white/20 uppercase tracking-widest mb-1.5">Sentiment Axis</p>
                    <div className="h-3 rounded-full" style={{
                        background: 'linear-gradient(to right, #ef4444, #f59e0b, #22c55e)'
                    }} />
                    <div className="flex justify-between mt-1">
                        <span className="text-[9px] text-red-400/60">Low</span>
                        <span className="text-[9px] text-green-400/60">High</span>
                    </div>
                </div>
            </div>

            {/* ── Center Panel: River (flex-1, dynamic) ───────────────────────── */}
            <motion.div layout className="flex-1 flex flex-col min-w-0 overflow-hidden">
                {/* Client header */}
                <div className="px-4 py-3 border-b border-white/5 flex-shrink-0 flex items-center justify-between">
                    <AnimatePresence mode="wait">
                        <motion.div
                            key={activeClientId}
                            initial={{ opacity: 0, y: -6 }}
                            animate={{ opacity: 1, y: 0 }}
                            exit={{ opacity: 0, y: 6 }}
                            transition={{ duration: 0.2 }}
                        >
                            <h4 className="text-white font-semibold text-sm">{activeClient.name}</h4>
                            <p className="text-white/40 text-[10px]">
                                {activeClient.events.length} events · {activeClient.stage}
                            </p>
                        </motion.div>
                    </AnimatePresence>
                    <div className="text-[10px] text-white/30 font-mono">
                        X = Sentiment Score
                    </div>
                </div>

                {/* River canvas */}
                <div className="flex-1 overflow-hidden relative">
                    <AnimatePresence mode="wait">
                        <motion.div
                            key={activeClientId}
                            initial={{ opacity: 0 }}
                            animate={{ opacity: 1 }}
                            exit={{ opacity: 0 }}
                            transition={{ duration: 0.3 }}
                            className="absolute inset-0"
                        >
                            <RiverPath
                                events={activeClient.events}
                                onSelectEvent={setSelectedEventId}
                                selectedEventId={selectedEventId}
                            />
                        </motion.div>
                    </AnimatePresence>
                </div>
            </motion.div>

            {/* ── Right Panel: Inspector (0 → 30%, slide-in) ──────────────────── */}
            <InspectorPanel
                event={selectedEvent}
                onClose={() => setSelectedEventId(null)}
            />
        </motion.div>
    );
}

