import React, { useRef, useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Phone, Eye, MessageSquare, TrendingUp } from 'lucide-react';
import type { JourneyEvent } from '@/types';
import { generateSmoothPath, sentimentToX, indexToY } from '@/utils/curveGenerator';

// ─── Icon map ─────────────────────────────────────────────────────────────────
const EVENT_ICONS: Record<JourneyEvent['type'], React.FC<React.SVGProps<SVGSVGElement>>> = {
    call: Phone,
    visit: Eye,
    chat: MessageSquare,
    negotiation: TrendingUp,
};

// ─── Colour stops for gradient ────────────────────────────────────────────────
// Gradient goes left (red, low sentiment) → amber → green (right, high sentiment)
const GRADIENT_ID = 'riverGradient';

interface RiverPathProps {
    events: JourneyEvent[];
    onSelectEvent: (id: string) => void;
    selectedEventId: string | null;
}

export function RiverPath({ events, onSelectEvent, selectedEventId }: RiverPathProps) {
    const containerRef = useRef<HTMLDivElement>(null);
    const [dims, setDims] = useState({ width: 600, height: 500 });
    const [hoveredId, setHoveredId] = useState<string | null>(null);

    // Measure container on mount and resize
    useEffect(() => {
        const el = containerRef.current;
        if (!el) return;
        const ro = new ResizeObserver(entries => {
            const { width, height } = entries[0].contentRect;
            setDims({ width: Math.max(width, 200), height: Math.max(height, 300) });
        });
        ro.observe(el);
        return () => ro.disconnect();
    }, []);

    const { width, height } = dims;
    const PAD_X = 48;
    const PAD_Y = 48;

    // Map events → pixel points
    const points = events.map((ev, i) => ({
        x: sentimentToX(ev.sentimentScore, width, PAD_X),
        y: indexToY(i, events.length, height, PAD_Y),
        ev,
    }));

    const pathD = generateSmoothPath(points.map(p => ({ x: p.x, y: p.y })), 0.45);

    return (
        <div ref={containerRef} className="relative w-full h-full overflow-hidden">
            {/* Subtle grid background */}
            <div
                className="absolute inset-0 pointer-events-none"
                style={{
                    backgroundImage:
                        'linear-gradient(rgba(255,255,255,0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.03) 1px, transparent 1px)',
                    backgroundSize: '32px 32px',
                }}
            />
            {/* Edge fade */}
            <div className="absolute inset-0 pointer-events-none"
                style={{
                    background: 'radial-gradient(ellipse at center, transparent 40%, rgba(0,0,0,0.6) 100%)',
                }}
            />

            {/* X-axis labels */}
            <div className="absolute bottom-2 left-0 right-0 flex justify-between px-12 pointer-events-none">
                <span className="text-[10px] text-red-400/60 font-mono">LOW</span>
                <span className="text-[10px] text-white/30 font-mono">SENTIMENT</span>
                <span className="text-[10px] text-green-400/60 font-mono">HIGH</span>
            </div>

            <svg
                width={width}
                height={height}
                className="absolute inset-0"
                style={{ overflow: 'visible' }}
            >
                <defs>
                    {/* Horizontal gradient: red → amber → green */}
                    <linearGradient id={GRADIENT_ID} x1="0%" y1="0%" x2="100%" y2="0%">
                        <stop offset="0%" stopColor="#ef4444" stopOpacity="0.9" />
                        <stop offset="40%" stopColor="#f59e0b" stopOpacity="0.9" />
                        <stop offset="100%" stopColor="#22c55e" stopOpacity="0.9" />
                    </linearGradient>

                    {/* Glow filter for active nodes */}
                    <filter id="nodeGlow" x="-50%" y="-50%" width="200%" height="200%">
                        <feGaussianBlur stdDeviation="4" result="blur" />
                        <feMerge>
                            <feMergeNode in="blur" />
                            <feMergeNode in="SourceGraphic" />
                        </feMerge>
                    </filter>

                    {/* Soft glow for the path itself */}
                    <filter id="pathGlow" x="-10%" y="-10%" width="120%" height="120%">
                        <feGaussianBlur stdDeviation="3" result="blur" />
                        <feMerge>
                            <feMergeNode in="blur" />
                            <feMergeNode in="SourceGraphic" />
                        </feMerge>
                    </filter>
                </defs>

                {/* Glow shadow path (blurred duplicate) */}
                {pathD && (
                    <path
                        d={pathD}
                        fill="none"
                        stroke={`url(#${GRADIENT_ID})`}
                        strokeWidth={10}
                        strokeLinecap="round"
                        opacity={0.25}
                        filter="url(#pathGlow)"
                    />
                )}

                {/* Main river path */}
                {pathD && (
                    <motion.path
                        d={pathD}
                        fill="none"
                        stroke={`url(#${GRADIENT_ID})`}
                        strokeWidth={5}
                        strokeLinecap="round"
                        initial={{ pathLength: 0, opacity: 0 }}
                        animate={{ pathLength: 1, opacity: 1 }}
                        transition={{ duration: 1.2, ease: 'easeInOut' }}
                    />
                )}

                {/* Event nodes */}
                {points.map(({ x, y, ev }) => {
                    const Icon = EVENT_ICONS[ev.type];
                    const isHovered = hoveredId === ev.id;
                    const isSelected = selectedEventId === ev.id;
                    const isActive = isHovered || isSelected;

                    // Colour based on sentiment
                    const nodeColor =
                        ev.sentimentScore >= 70 ? '#22c55e' :
                            ev.sentimentScore >= 40 ? '#f59e0b' : '#ef4444';

                    return (
                        <g key={ev.id}>
                            {/* Pulse ring (idle) */}
                            {!isActive && (
                                <motion.circle
                                    cx={x} cy={y} r={14}
                                    fill="none"
                                    stroke={nodeColor}
                                    strokeWidth={1}
                                    opacity={0.4}
                                    animate={{ r: [12, 18, 12], opacity: [0.4, 0.1, 0.4] }}
                                    transition={{ duration: 2.5, repeat: Infinity, ease: 'easeInOut' }}
                                />
                            )}

                            {/* Node background */}
                            <motion.circle
                                cx={x} cy={y}
                                r={isActive ? 18 : 12}
                                fill={`${nodeColor}22`}
                                stroke={nodeColor}
                                strokeWidth={isActive ? 2 : 1.5}
                                style={isActive ? { filter: `drop-shadow(0 0 8px ${nodeColor})` } : {}}
                                animate={{ r: isActive ? 18 : 12 }}
                                transition={{ type: 'spring', stiffness: 300, damping: 20 }}
                                className="cursor-pointer"
                                onMouseEnter={() => setHoveredId(ev.id)}
                                onMouseLeave={() => setHoveredId(null)}
                                onClick={() => onSelectEvent(ev.id)}
                            />

                            {/* Icon (foreignObject for React icons) */}
                            <foreignObject
                                x={x - 8} y={y - 8}
                                width={16} height={16}
                                className="pointer-events-none"
                            >
                                <div className="w-4 h-4 flex items-center justify-center">
                                    {React.createElement(Icon, {
                                        style: { width: 10, height: 10, color: nodeColor, strokeWidth: 2.5 }
                                    })}
                                </div>
                            </foreignObject>

                            {/* Hover label */}
                            {isHovered && !isSelected && (
                                <motion.g
                                    initial={{ opacity: 0, y: -4 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    transition={{ duration: 0.15 }}
                                >
                                    <rect
                                        x={x - 60} y={y - 42}
                                        width={120} height={26}
                                        rx={6}
                                        fill="rgba(0,0,0,0.85)"
                                        stroke={nodeColor}
                                        strokeWidth={0.8}
                                        strokeOpacity={0.6}
                                    />
                                    <text
                                        x={x} y={y - 24}
                                        textAnchor="middle"
                                        fill="white"
                                        fontSize={10}
                                        fontFamily="Inter, sans-serif"
                                        fontWeight={500}
                                    >
                                        {ev.title}
                                    </text>
                                    <text
                                        x={x} y={y - 13}
                                        textAnchor="middle"
                                        fill={nodeColor}
                                        fontSize={8.5}
                                        fontFamily="Inter, sans-serif"
                                    >
                                        {ev.sentimentScore}% sentiment
                                    </text>
                                </motion.g>
                            )}
                        </g>
                    );
                })}
            </svg>
        </div>
    );
}
