import React, { useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { FileSelector } from './FileSelector';
import { GeminiSettings } from './GeminiSettings';
import { VideoTimeline } from './VideoTimeline';
import { ProcessingAnimation } from './ProcessingAnimation';

interface FileState {
  path: string;
  name: string;
}

interface TranscriptionState {
  narrative: string;
}

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

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

interface TranscriptionTaskProps {
  apiKey: string;
  visualPrompt: string;
  subtitlePrompt: string;
}

export const TranscriptionTask: React.FC<TranscriptionTaskProps> = ({
  apiKey,
  visualPrompt,
  subtitlePrompt,
}) => {
  const [videoFile, setVideoFile] = useState<FileState | null>(null);
  const [subtitleFile, setSubtitleFile] = useState<FileState | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedFrames, setSelectedFrames] = useState<SelectedFrame[]>([]);
  const [transcription, setTranscription] = useState<TranscriptionState | null>(null);
  const [thumbnails, setThumbnails] = useState<Thumbnail[]>([]);

  const handleVideoSelect = (path: string) => {
    const name = path.split('/').pop() || '';
    setVideoFile({ path, name });
    setThumbnails([]); // Clear thumbnails when new video is selected
  };

  const handleSubtitleSelect = (path: string) => {
    const name = path.split('/').pop() || '';
    setSubtitleFile({ path, name });
  };

  const handleThumbnailsGenerated = (newThumbnails: Thumbnail[]) => {
    setThumbnails(newThumbnails);
  };

  const handleGenerateTranscription = async () => {
    if (!videoFile || selectedFrames.length === 0) {
      setError('Please select a video and at least one frame');
      return;
    }

    setIsProcessing(true);
    setError(null);
    setTranscription(null);

    try {
      console.log('Starting transcription process...');
      
      const transcriptionResult = await invoke<TranscriptionState>('process_transcription', {
        args: {
          video_path: videoFile.path,
          subtitle_path: subtitleFile?.path,
          selected_frames: selectedFrames.map(frame => ({
            path: frame.path,
            time: frame.time,
            base64_image: frame.base64Image
          })),
          api_key: apiKey,
          visual_prompt: visualPrompt,
          subtitle_prompt: subtitlePrompt
        }
      });
      
      // Clean the content
      const narrative = String(transcriptionResult.narrative || '').trim();
      
      setTranscription({
        narrative
      });
      
    } catch (error) {
      console.error('Transcription error:', error);
      setError(`Transcription error: ${error}`);
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <div className="flex-1 mr-4">
            <p className="text-sm text-gray-600 mb-2">Video file:</p>
            <p className="text-gray-800">{videoFile?.name || 'No file selected'}</p>
          </div>
          <FileSelector
            label="Select Video"
            onFileSelect={handleVideoSelect}
            accept={['mp4', 'avi', 'mov', 'mkv']}
          />
        </div>

        <div className="flex items-center justify-between">
          <div className="flex-1 mr-4">
            <p className="text-sm text-gray-600 mb-2">Subtitle file (optional):</p>
            <p className="text-gray-800">{subtitleFile?.name || 'No file selected'}</p>
          </div>
          <FileSelector
            label="Select Subtitle"
            onFileSelect={handleSubtitleSelect}
            accept={['srt', 'ass']}
          />
        </div>
      </div>

      <GeminiSettings 
        videoFile={videoFile?.path || null}
        onThumbnailsGenerated={handleThumbnailsGenerated}
      />

      {videoFile && (
        <VideoTimeline
          videoPath={videoFile.path}
          onFramesSelect={setSelectedFrames}
          thumbnails={thumbnails}
        />
      )}

      {isProcessing && <ProcessingAnimation />}

      {transcription && (
        <div className="mt-6 space-y-4">
          <h3 className="text-lg font-semibold">Scene Narrative</h3>
          <div className="h-[400px] overflow-y-auto p-4 bg-gray-50 rounded-lg text-sm">
            <div className="bg-white p-4 rounded border border-gray-200">
              <p className="whitespace-pre-wrap leading-relaxed">{transcription.narrative}</p>
            </div>
          </div>
        </div>
      )}

      {error && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4">
          <strong className="font-bold">Error: </strong>
          <span className="block sm:inline">{error}</span>
        </div>
      )}

      <button
        onClick={handleGenerateTranscription}
        disabled={!videoFile || selectedFrames.length === 0 || isProcessing}
        className={`w-full px-4 py-2 rounded-md text-white font-medium ${
          !videoFile || selectedFrames.length === 0 || isProcessing
            ? 'bg-gray-400 cursor-not-allowed'
            : 'bg-blue-500 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500'
        }`}
      >
        {isProcessing ? 'Generating Transcription...' : 'Generate Transcription'}
      </button>
    </div>
  );
};
