import React, { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';

interface VideoTimelineProps {
  videoPath: string | null;
  onFramesSelect: (frames: SelectedFrame[]) => void;
  thumbnails: Thumbnail[];
}

interface Thumbnail {
  path: string;
  time: number;
}

interface SelectedFrame {
  path: string;
  time: number;
  base64Image: string;
  description?: string;
}

export const VideoTimeline: React.FC<VideoTimelineProps> = ({ videoPath, onFramesSelect, thumbnails }) => {
  const [selectedFrames, setSelectedFrames] = useState<SelectedFrame[]>([]);
  const [thumbnailUrls, setThumbnailUrls] = useState<{ [key: string]: string }>({});

  useEffect(() => {
    const loadThumbnails = async () => {
      const urls: { [key: string]: string } = {};
      for (const thumb of thumbnails) {
        try {
          const base64 = await invoke<string>('read_thumbnail', { path: thumb.path });
          urls[thumb.path] = `data:image/jpeg;base64,${base64}`;
        } catch (error) {
          console.error('Error loading thumbnail:', error);
        }
      }
      setThumbnailUrls(urls);
    };

    loadThumbnails();
  }, [thumbnails]);

  const formatTime = (seconds: number): string => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  };

  if (!videoPath) {
    return null;
  }

  return (
    <div className="p-4 bg-gray-50 rounded-lg">
      <div className="flex justify-between items-center mb-2">
        <label className="block text-sm font-medium text-gray-700">
          Select Scene Frames
        </label>
        <span className="text-sm text-gray-500">
          {selectedFrames.length} frames selected
        </span>
      </div>

      <div className="mb-4">
        <div className="text-sm text-gray-600 mb-2">
          Click thumbnails to select frames for scene descriptions. Selected frames will be analyzed in chronological order.
        </div>
      </div>

      <div className="flex overflow-x-auto space-x-2 pb-2">
        {thumbnails.map((thumb, index) => (
          <div
            key={index}
            className={`relative flex-shrink-0 cursor-pointer ${
              selectedFrames.some(f => Math.abs(f.time - thumb.time) < 2) 
                ? 'ring-2 ring-blue-500' 
                : 'hover:ring-2 hover:ring-blue-300'
            }`}
            onClick={async () => {
              const isSelected = selectedFrames.some(
                f => Math.abs(f.time - thumb.time) < 2
              );

              if (isSelected) {
                // Remove from selection
                const newFrames = selectedFrames.filter(
                  f => Math.abs(f.time - thumb.time) >= 2
                );
                setSelectedFrames(newFrames);
                onFramesSelect(newFrames);
              } else {
                // Add to selection
                try {
                  const base64 = await invoke<string>('read_thumbnail', { 
                    path: thumb.path 
                  });
                  const newFrame: SelectedFrame = {
                    path: thumb.path,
                    time: thumb.time,
                    base64Image: base64
                  };
                  const newFrames = [...selectedFrames, newFrame].sort(
                    (a, b) => a.time - b.time
                  );
                  setSelectedFrames(newFrames);
                  onFramesSelect(newFrames);
                } catch (error) {
                  console.error('Error loading thumbnail:', error);
                }
              }
            }}
          >
            {thumbnailUrls[thumb.path] && (
              <img
                src={thumbnailUrls[thumb.path]}
                alt={`Thumbnail at ${formatTime(thumb.time)}`}
                className="h-20 w-36 object-cover rounded"
              />
            )}
            <div className="absolute bottom-0 left-0 right-0 bg-black bg-opacity-50 text-white text-xs text-center py-1">
              {formatTime(thumb.time)}
            </div>
            {selectedFrames.some(f => Math.abs(f.time - thumb.time) < 2) && (
              <div className="absolute top-2 right-2 bg-blue-500 text-white rounded-full w-5 h-5 flex items-center justify-center text-xs">
                {selectedFrames.findIndex(f => Math.abs(f.time - thumb.time) < 2) + 1}
              </div>
            )}
          </div>
        ))}
      </div>

      {selectedFrames.length > 0 && (
        <div className="mt-4">
          <div className="text-sm font-medium text-gray-700 mb-2">
            Selected Frames Order:
          </div>
          <div className="flex flex-wrap gap-2">
            {selectedFrames.map((frame, index) => (
              <div key={index} className="text-sm text-gray-600 bg-gray-100 rounded px-2 py-1">
                {index + 1}. {formatTime(frame.time)}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};
