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

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

export const MergeTask: React.FC = () => {
  const [videoFile, setVideoFile] = useState<FileState | null>(null);
  const [subtitleFile, setSubtitleFile] = useState<FileState | null>(null);
  const [progress, setProgress] = useState<number>(0);
  const [isProcessing, setIsProcessing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [addBlackBar, setAddBlackBar] = useState(true);
  const [resizeTo720p, setResizeTo720p] = useState(true);

  useEffect(() => {
    let intervalId: number | undefined;

    if (isProcessing) {
      // Poll for progress every 100ms while processing
      intervalId = window.setInterval(async () => {
        try {
          const currentProgress = await invoke<number>('get_progress');
          setProgress(currentProgress);
        } catch (error) {
          console.error('Failed to get progress:', error);
        }
      }, 100);
    }

    return () => {
      if (intervalId !== undefined) {
        window.clearInterval(intervalId);
      }
    };
  }, [isProcessing]);

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

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

  const handleMerge = async () => {
    if (!videoFile || !subtitleFile) return;

    setIsProcessing(true);
    setProgress(0);
    setError(null);

    try {
      const mergeResult = await invoke<string>('merge_video_subtitle', {
        args: {
          video_path: videoFile.path,
          subtitle_path: subtitleFile.path,
          add_black_bar: addBlackBar,
          resize_to_720p: resizeTo720p
        }
      });

      console.log('Merge completed:', mergeResult);
      setProgress(100);
    } catch (error) {
      console.error('Error merging files:', error);
      setError(error as string);
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <div className="space-y-6">
      <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:</p>
          <p className="text-gray-800">{subtitleFile?.name || 'No file selected'}</p>
        </div>
        <FileSelector
          label="Select Subtitle"
          onFileSelect={handleSubtitleSelect}
          accept={['srt', 'ass']}
        />
      </div>

      <div className="space-y-3">
        <label className="flex items-center space-x-2">
          <input
            type="checkbox"
            checked={addBlackBar}
            onChange={(e) => setAddBlackBar(e.target.checked)}
            className="h-4 w-4 text-blue-500 rounded border-gray-300 focus:ring-blue-500"
          />
          <span>Add black bar for subtitles</span>
        </label>

        <label className="flex items-center space-x-2">
          <input
            type="checkbox"
            checked={resizeTo720p}
            onChange={(e) => setResizeTo720p(e.target.checked)}
            className="h-4 w-4 text-blue-500 rounded border-gray-300 focus:ring-blue-500"
          />
          <span>Resize to 720p resolution</span>
        </label>
      </div>

      <div className="space-y-2">
        <div className="h-2.5 bg-gray-200 rounded-full">
          <div 
            className="h-2.5 bg-blue-600 rounded-full transition-all duration-300"
            style={{ width: `${progress}%` }}
          />
        </div>
        <p className="text-center text-sm text-gray-600">
          {isProcessing ? `${Math.round(progress)}%` : ''}
        </p>
      </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={handleMerge}
        disabled={!videoFile || !subtitleFile || isProcessing}
        className={`w-full px-4 py-2 rounded-md text-white font-medium ${
          !videoFile || !subtitleFile || 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 ? 'Merging...' : 'Merge Video and Subtitle'}
      </button>
    </div>
  );
};
