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

interface GeminiSettingsProps {
  videoFile: string | null;
  onThumbnailsGenerated: (thumbnails: { path: string; time: number; }[]) => void;
}

export const GeminiSettings: React.FC<GeminiSettingsProps> = ({ 
  videoFile, 
  onThumbnailsGenerated 
}) => {
  const [generatingThumbnails, setGeneratingThumbnails] = useState(false);
  const [thumbnailResult, setThumbnailResult] = useState<string | null>(null);

  const generateThumbnails = useCallback(async () => {
    if (!videoFile) {
      setThumbnailResult("Please select a video file before generating thumbnails");
      return;
    }

    setGeneratingThumbnails(true);
    setThumbnailResult(null);
    try {
      const thumbnails = await invoke<{ path: string; time: number; }[]>('generate_thumbnails', { videoPath: videoFile });
      onThumbnailsGenerated(thumbnails);
      setThumbnailResult("Thumbnails generated successfully!");
    } catch (error) {
      setThumbnailResult(`Error: ${error}`);
    } finally {
      setGeneratingThumbnails(false);
    }
  }, [videoFile, onThumbnailsGenerated]);

  return (
    <div className="space-y-4 p-4 bg-gray-50 rounded-lg">
      <div className="space-y-3">
        <button
          onClick={generateThumbnails}
          disabled={generatingThumbnails || !videoFile}
          className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-500 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
        >
          {generatingThumbnails ? (
            <>
              <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              Generating...
            </>
          ) : (
            'Generate Thumbnails'
          )}
        </button>

        {thumbnailResult && (
          <div className={`text-sm ${thumbnailResult.startsWith('Error') || thumbnailResult.startsWith('Please') ? 'text-red-600' : 'text-green-600'}`}>
            {thumbnailResult}
          </div>
        )}
      </div>
    </div>
  );
};
