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

interface SettingsProps {
  isOpen: boolean;
  onClose: () => void;
  apiKey: string;
  onApiKeyChange: (key: string) => void;
  visualPrompt: string;
  subtitlePrompt: string;
  onVisualPromptChange: (prompt: string) => void;
  onSubtitlePromptChange: (prompt: string) => void;
}

// Note: We keep subtitle prompt in Settings since it's still used by the merge task

export const DEFAULT_API_KEY = 'AIzaSyAF825tPTh77oL0knsGFEyvsN0iPUO_bXc';
export const DEFAULT_VISUAL_PROMPT = `Analyze this video frame from timestamp {} and provide a visual description focusing on:
1. The visual setup and environment
2. The people present, their appearance, and positioning
3. Any relevant visual context or background details
4. Do not include details about the individuals' hands

Format the description in clear, concise paragraphs that would be helpful for DeafBlind readers to understand the visual context. Focus on spatial relationships and important visual details that contribute to understanding the scene. Use maximum of 200 words and do not include your own thoughts-- just provide the visual description alone.`;

// Note: We keep subtitle prompt since it's still used by the merge task
export const DEFAULT_SUBTITLE_PROMPT = `I will provide you with timestamped scene descriptions and subtitle content. Create a chronological narrative that combines these elements with these strict rules:

Required Format Rules:
1. Use ONLY the exact dialogue lines from the subtitle content - do not add, modify, or create new dialogue but feel free to turn them into paragraphs provided that content of exact words are not modified.
2. For the first scene description, MOVE it to the beginning of the narration. For the rest of the scenes, ensure that they are located according to their exact timestamps when they occur in the dialogue flow.
3. Keep all dialogue in strict chronological order and to be quoted verbatim
4. For multiple speakers, add speaker identification before their lines until the next speaker's dialogue lines. If there is only one speaker, do not add a speaker identifier.
5. Include speaking manner (e.g., "warmly", "firmly") only when clearly implied by the subtitle text
6. Use paragraph breaks to separate different scenes if there is more than one scene
7. Ensure that there are no timestamps in the output including for the scenes

Critical Requirements:
- Do not invent or modify any dialogue
- Only use the provided subtitle text verbatim
- Scene descriptions should be inserted exactly where their timestamps occur except for the first scene which is to start at the beginning of the narration
- Maintain precise chronological order of all elements
- Keep your thoughts and ideas to yourself

Format the output as a flowing narrative that preserves all original dialogue while weaving in the visual context at the appropriate moments as like it's a novel.`;

export const Settings: React.FC<SettingsProps> = ({ 
  isOpen, 
  onClose, 
  apiKey, 
  onApiKeyChange,
  visualPrompt,
  subtitlePrompt,
  onVisualPromptChange,
  onSubtitlePromptChange
}) => {
  const [testing, setTesting] = useState(false);
  const [testResult, setTestResult] = useState<string | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [displayValue, setDisplayValue] = useState('*'.repeat(apiKey.length));

  useEffect(() => {
    if (!isEditing) {
      setDisplayValue('*'.repeat(apiKey.length));
    }
  }, [apiKey, isEditing]);

  const handleApiKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = e.target.value;
    onApiKeyChange(newValue);
    if (!isEditing) {
      setDisplayValue('*'.repeat(newValue.length));
    }
  };

  const handleFocus = () => {
    setIsEditing(true);
    setDisplayValue(apiKey);
  };

  const handleBlur = () => {
    setIsEditing(false);
    setDisplayValue('*'.repeat(apiKey.length));
  };

  const resetApiKeyToDefault = () => {
    onApiKeyChange(DEFAULT_API_KEY);
  };

  const resetVisualPromptToDefault = () => {
    onVisualPromptChange(DEFAULT_VISUAL_PROMPT);
  };

  const resetSubtitlePromptToDefault = () => {
    onSubtitlePromptChange(DEFAULT_SUBTITLE_PROMPT);
  };

  const testApiKey = async () => {
    setTesting(true);
    setTestResult(null);
    try {
      await invoke('test_gemini_api', { apiKey });
      setTestResult('API key is valid');
    } catch (error) {
      setTestResult(`Error: ${error}`);
    } finally {
      setTesting(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg p-6 w-[500px] max-w-full">
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-xl font-semibold">Settings</h2>
          <button
            onClick={onClose}
            className="text-gray-500 hover:text-gray-700"
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div className="space-y-4">
          <div>
            <label htmlFor="apiKey" className="block text-sm font-medium text-gray-700 mb-1">
              Gemini API Key
            </label>
            <input
              type="text"
              id="apiKey"
              value={isEditing ? apiKey : displayValue}
              onChange={handleApiKeyChange}
              onFocus={handleFocus}
              onBlur={handleBlur}
              className="w-full px-3 py-2 rounded-md border border-gray-300 focus:ring-blue-500 focus:border-blue-500 sm:text-sm font-mono"
              placeholder="Enter your Gemini API key"
              spellCheck={false}
              autoComplete="off"
            />
          </div>

          <div className="flex space-x-3">
            <button
              onClick={testApiKey}
              disabled={testing}
              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"
            >
              {testing ? 'Testing...' : 'Test API Key'}
            </button>

            {apiKey !== DEFAULT_API_KEY && (
              <button
                onClick={resetApiKeyToDefault}
                className="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
              >
                Reset to Default
              </button>
            )}
          </div>

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

          <div className="mt-6 space-y-4">
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">
                Visual Description Prompt
              </label>
              <div className="relative">
                <textarea
                  value={visualPrompt}
                  onChange={(e) => onVisualPromptChange(e.target.value)}
                  rows={4}
                  className="w-full px-3 py-2 rounded-md border border-gray-300 focus:ring-blue-500 focus:border-blue-500 sm:text-sm font-mono resize-y"
                  placeholder="Enter prompt for visual description"
                  spellCheck={false}
                />
                <div className="absolute bottom-2 right-2 text-xs text-gray-500">
                  {visualPrompt.length} characters
                </div>
              </div>
              {visualPrompt !== DEFAULT_VISUAL_PROMPT && (
                <button
                  onClick={resetVisualPromptToDefault}
                  className="inline-flex items-center px-3 py-1 border border-gray-300 text-xs font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                >
                  Reset to Default
                </button>
              )}
            </div>

            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">
                Subtitle Narrative Prompt
              </label>
              <div className="relative">
                <textarea
                  value={subtitlePrompt}
                  onChange={(e) => onSubtitlePromptChange(e.target.value)}
                  rows={4}
                  className="w-full px-3 py-2 rounded-md border border-gray-300 focus:ring-blue-500 focus:border-blue-500 sm:text-sm font-mono resize-y"
                  placeholder="Enter prompt for subtitle narrative"
                  spellCheck={false}
                />
                <div className="absolute bottom-2 right-2 text-xs text-gray-500">
                  {subtitlePrompt.length} characters
                </div>
              </div>
              {subtitlePrompt !== DEFAULT_SUBTITLE_PROMPT && (
                <button
                  onClick={resetSubtitlePromptToDefault}
                  className="inline-flex items-center px-3 py-1 border border-gray-300 text-xs font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                >
                  Reset to Default
                </button>
              )}
            </div>
          </div>
        </div>

        <div className="mt-6 flex justify-end border-t border-gray-200 pt-4">
          <button
            onClick={onClose}
            className="px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-500 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
          >
            Close
          </button>
        </div>
      </div>
    </div>
  );
};
