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;
  onOpenSettings?: () => void;
}

export const TranscriptionTask: React.FC<TranscriptionTaskProps> = ({
  apiKey,
  visualPrompt,
  subtitlePrompt,
  onOpenSettings
}) => {
  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 [copySuccess, setCopySuccess] = useState(false);

  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">
      {!apiKey && (
        <div className="bg-amber-50 border-l-4 border-amber-400 p-4 mb-4">
          <div className="flex">
            <div className="flex-shrink-0">
              <svg className="h-5 w-5 text-amber-400" viewBox="0 0 20 20" fill="currentColor">
                <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
              </svg>
            </div>
            <div className="ml-3">
              <p className="text-sm text-amber-700">
                A Gemini API Key is required to generate video descriptions. 
                <button
                  onClick={onOpenSettings}
                  className="ml-2 font-medium text-amber-700 underline hover:text-amber-600"
                >
                  Add API Key in Settings
                </button>
              </p>
            </div>
          </div>
        </div>
      )}
      <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="space-y-2">
            <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 className="flex items-center space-x-3">
              <button
                onClick={(e) => {
                  e.preventDefault(); // Prevent any navigation
                  navigator.clipboard.writeText(transcription.narrative)
                    .then(() => {
                      setCopySuccess(true);
                      setTimeout(() => setCopySuccess(false), 2000);
                    })
                    .catch(err => console.error('Failed to copy:', err));
                }}
                className="px-4 py-2 text-sm font-medium text-white bg-blue-500 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
              >
                Copy to Clipboard
              </button>
              {copySuccess && (
                <span className="text-sm text-green-600 animate-fade-in">
                  Content copied successfully!
                </span>
              )}
            </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>
  );
};
