'use client';

import { useEffect, useRef, useState, useCallback } from 'react';
import { cn } from '@/lib/utils';

interface ConnectionDef {
  /** Route id — used as key */
  routeId: string;
  /** Index of phone card on the left (0-based) */
  leftIndex: number;
  /** Index of bot card on the right (0-based) */
  rightIndex: number;
  active: boolean;
}

interface ConnectionLinesProps {
  connections: ConnectionDef[];
  leftContainerRef: React.RefObject<HTMLDivElement>;
  rightContainerRef: React.RefObject<HTMLDivElement>;
  centerRef: React.RefObject<HTMLDivElement>;
  highlightedRouteId: string | null;
}

interface LinePath {
  routeId: string;
  d: string;
  active: boolean;
}

export default function ConnectionLines({
  connections,
  leftContainerRef,
  rightContainerRef,
  centerRef,
  highlightedRouteId,
}: ConnectionLinesProps) {
  const [paths, setPaths] = useState<LinePath[]>([]);
  const svgRef = useRef<SVGSVGElement>(null);

  const computePaths = useCallback(() => {
    if (!centerRef.current || !leftContainerRef.current || !rightContainerRef.current) return;

    const centerRect = centerRef.current.getBoundingClientRect();
    const leftCards = leftContainerRef.current.querySelectorAll('[data-phone-card]');
    const rightCards = rightContainerRef.current.querySelectorAll('[data-bot-card]');

    const newPaths: LinePath[] = [];

    for (const conn of connections) {
      const leftCard = leftCards[conn.leftIndex] as HTMLElement | undefined;
      const rightCard = rightCards[conn.rightIndex] as HTMLElement | undefined;

      if (!leftCard || !rightCard) continue;

      const leftRect = leftCard.getBoundingClientRect();
      const rightRect = rightCard.getBoundingClientRect();

      // Points relative to center SVG
      const x1 = leftRect.right - centerRect.left;
      const y1 = leftRect.top + leftRect.height / 2 - centerRect.top;
      const x2 = rightRect.left - centerRect.left;
      const y2 = rightRect.top + rightRect.height / 2 - centerRect.top;

      // Control points for smooth bezier
      const cpOffset = Math.min(Math.abs(x2 - x1) * 0.45, 120);
      const cp1x = x1 + cpOffset;
      const cp1y = y1;
      const cp2x = x2 - cpOffset;
      const cp2y = y2;

      const d = `M ${x1} ${y1} C ${cp1x} ${cp1y}, ${cp2x} ${cp2y}, ${x2} ${y2}`;
      newPaths.push({ routeId: conn.routeId, d, active: conn.active });
    }

    setPaths(newPaths);
  }, [connections, centerRef, leftContainerRef, rightContainerRef]);

  useEffect(() => {
    computePaths();

    const resizeObserver = new ResizeObserver(() => {
      requestAnimationFrame(computePaths);
    });

    if (centerRef.current) resizeObserver.observe(centerRef.current);
    if (leftContainerRef.current) resizeObserver.observe(leftContainerRef.current);
    if (rightContainerRef.current) resizeObserver.observe(rightContainerRef.current);

    window.addEventListener('resize', computePaths);
    window.addEventListener('scroll', computePaths, true);

    return () => {
      resizeObserver.disconnect();
      window.removeEventListener('resize', computePaths);
      window.removeEventListener('scroll', computePaths, true);
    };
  }, [computePaths, centerRef, leftContainerRef, rightContainerRef]);

  if (paths.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center h-full text-slate-600 gap-3">
        <svg className="h-12 w-12 opacity-30" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
        </svg>
        <p className="text-xs font-medium uppercase tracking-wider">No active routes</p>
      </div>
    );
  }

  return (
    <>
      {/* CSS for animated dash */}
      <style jsx>{`
        @keyframes dash-flow {
          to { stroke-dashoffset: -24; }
        }
        @keyframes pulse-line {
          0%, 100% { opacity: 0.7; }
          50% { opacity: 1; }
        }
        .connection-line {
          animation: dash-flow 1.5s linear infinite, pulse-line 3s ease-in-out infinite;
        }
        .connection-line-highlight {
          animation: dash-flow 0.8s linear infinite;
        }
        .connection-glow {
          animation: pulse-line 2s ease-in-out infinite;
        }
      `}</style>

      <svg
        ref={svgRef}
        className="absolute inset-0 w-full h-full pointer-events-none"
        style={{ overflow: 'visible' }}
      >
        <defs>
          {/* Glow filter */}
          <filter id="line-glow" x="-20%" y="-20%" width="140%" height="140%">
            <feGaussianBlur in="SourceGraphic" stdDeviation="3" result="blur" />
            <feMerge>
              <feMergeNode in="blur" />
              <feMergeNode in="SourceGraphic" />
            </feMerge>
          </filter>

          {/* Stronger glow for highlighted */}
          <filter id="line-glow-strong" x="-30%" y="-30%" width="160%" height="160%">
            <feGaussianBlur in="SourceGraphic" stdDeviation="5" result="blur" />
            <feMerge>
              <feMergeNode in="blur" />
              <feMergeNode in="blur" />
              <feMergeNode in="SourceGraphic" />
            </feMerge>
          </filter>
        </defs>

        {paths.map((p) => {
          const isHighlighted = highlightedRouteId === p.routeId;
          const isDimmed = highlightedRouteId !== null && !isHighlighted;

          return (
            <g key={p.routeId}>
              {/* Background glow line */}
              <path
                d={p.d}
                fill="none"
                stroke={p.active ? '#22d3ee' : '#475569'}
                strokeWidth={isHighlighted ? 4 : 2.5}
                strokeLinecap="round"
                className={cn(
                  isDimmed ? 'opacity-10' : '',
                  isHighlighted ? 'connection-glow' : ''
                )}
                filter={isHighlighted ? 'url(#line-glow-strong)' : 'url(#line-glow)'}
                style={{
                  opacity: isDimmed ? 0.1 : isHighlighted ? 1 : 0.25,
                  transition: 'opacity 0.3s ease',
                }}
              />

              {/* Animated foreground line */}
              <path
                d={p.d}
                fill="none"
                stroke={p.active ? '#22d3ee' : '#64748b'}
                strokeWidth={isHighlighted ? 2.5 : 1.5}
                strokeLinecap="round"
                strokeDasharray="8 16"
                className={cn(
                  isHighlighted ? 'connection-line-highlight' : 'connection-line',
                )}
                style={{
                  opacity: isDimmed ? 0.08 : isHighlighted ? 1 : 0.6,
                  transition: 'opacity 0.3s ease',
                }}
              />

              {/* Endpoint dots */}
              {!isDimmed && (
                <>
                  <circle
                    cx={p.d.match(/^M ([\d.]+)/)?.[1]}
                    cy={p.d.match(/^M [\d.]+ ([\d.]+)/)?.[1]}
                    r={isHighlighted ? 4 : 3}
                    fill={p.active ? '#22d3ee' : '#64748b'}
                    style={{ opacity: isHighlighted ? 1 : 0.7 }}
                    filter={isHighlighted ? 'url(#line-glow)' : undefined}
                  />
                  <circle
                    cx={p.d.match(/, ([\d.]+) ([\d.]+)$/)?.[1]}
                    cy={p.d.match(/, ([\d.]+) ([\d.]+)$/)?.[2]}
                    r={isHighlighted ? 4 : 3}
                    fill={p.active ? '#22d3ee' : '#64748b'}
                    style={{ opacity: isHighlighted ? 1 : 0.7 }}
                    filter={isHighlighted ? 'url(#line-glow)' : undefined}
                  />
                </>
              )}
            </g>
          );
        })}
      </svg>
    </>
  );
}
