import { useRef, useEffect } from 'react';
import type { VTTCue } from '../../lib/vtt';

interface SyncedCaptionListProps {
  cues: VTTCue[];
  currentTime: number;
  onSeek: (time: number) => void;
}

function formatTime(seconds: number): string {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);

  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`;
}

export function SyncedCaptionList({ cues, currentTime, onSeek }: SyncedCaptionListProps) {
  const containerRef = useRef<HTMLDivElement>(null);

  // Find current active cue
  const currentCueIndex = cues.findIndex(
    (cue) => currentTime >= cue.startTime && currentTime <= cue.endTime
  );

  // Auto-scroll to current caption
  useEffect(() => {
    if (currentCueIndex === -1 || !containerRef.current) return;

    const container = containerRef.current;
    const captionElements = container.children;
    const currentElement = captionElements[currentCueIndex] as HTMLElement;

    if (!currentElement) return;

    // Get actual rendered positions
    const elementRect = currentElement.getBoundingClientRect();
    const containerRect = container.getBoundingClientRect();

    // Calculate element position relative to container
    const elementTopInContainer = elementRect.top - containerRect.top + container.scrollTop;
    const elementBottomInContainer = elementTopInContainer + elementRect.height;

    const containerHeight = container.clientHeight;
    const currentScrollTop = container.scrollTop;
    const visibleTop = currentScrollTop;
    const visibleBottom = currentScrollTop + containerHeight;

    // Check if element is outside visible area
    const isAbove = elementTopInContainer < visibleTop;
    const isBelow = elementBottomInContainer > visibleBottom;

    if (isAbove || isBelow) {
      // Calculate scroll position to center the element
      const targetScrollTop = elementTopInContainer - (containerHeight / 2) + (elementRect.height / 2);

      container.scrollTo({
        top: Math.max(0, targetScrollTop),
        behavior: 'smooth',
      });
    }
  }, [currentCueIndex]);

  if (cues.length === 0) {
    return (
      <div className="bg-white border border-gray-200 rounded-lg p-4">
        <div className="text-center text-gray-500 text-sm">
          No captions available
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white border border-gray-200 rounded-lg p-4">
      <h4 className="font-medium text-gray-900 mb-3 text-sm">
        Caption Timeline ({cues.length} cues)
      </h4>
      <div
        ref={containerRef}
        className="max-h-48 overflow-y-auto space-y-2"
      >
        {cues.map((cue, index) => {
          const isActive = currentTime >= cue.startTime && currentTime <= cue.endTime;

          return (
            <div
              key={index}
              className={`
                p-2 rounded cursor-pointer transition-colors
                ${isActive
                  ? 'bg-blue-100 border border-blue-300'
                  : 'bg-gray-50 hover:bg-gray-100'
                }
              `}
              onClick={() => onSeek(cue.startTime)}
            >
              <div className="flex justify-between items-start">
                <div className="text-xs font-mono text-gray-600">
                  {formatTime(cue.startTime)} → {formatTime(cue.endTime)}
                </div>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onSeek(cue.startTime);
                  }}
                  className="text-xs text-blue-600 hover:text-blue-800"
                >
                  Jump
                </button>
              </div>
              <div className="text-sm text-gray-900 mt-1 whitespace-pre-wrap">
                {cue.text}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
