import { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { LazyStore } from '@tauri-apps/plugin-store';
import { Settings, DEFAULT_VISUAL_PROMPT, DEFAULT_SUBTITLE_PROMPT } from './components/Settings';
import { TranscriptionTask } from './components/TranscriptionTask';
import { MergeTask } from './components/MergeTask';
import './styles/index.css';

type TaskType = 'transcription' | 'merge' | null;

function App() {
  const [selectedTask, setSelectedTask] = useState<TaskType>(null);
  const [error, setError] = useState<string | null>(null);
  const [isSettingsOpen, setIsSettingsOpen] = useState(false);
  const [apiKey, setApiKey] = useState('');
  const [store] = useState(() => new LazyStore('settings.json'));

  // Load API key from store on mount
  useEffect(() => {
    store.get<string>('apiKey').then((savedKey) => {
      if (savedKey) {
        setApiKey(savedKey);
      }
    });
  }, [store]);

  // Save API key to store when it changes
  useEffect(() => {
    if (apiKey) {
      store.set('apiKey', apiKey);
    }
  }, [apiKey, store]);
  const [visualPrompt, setVisualPrompt] = useState(DEFAULT_VISUAL_PROMPT);
  const [subtitlePrompt, setSubtitlePrompt] = useState(DEFAULT_SUBTITLE_PROMPT);

  // Load prompts from store on mount
  useEffect(() => {
    store.get<string>('visualPrompt').then((saved) => {
      if (saved) {
        setVisualPrompt(saved);
      }
    });
    store.get<string>('subtitlePrompt').then((saved) => {
      if (saved) {
        setSubtitlePrompt(saved);
      }
    });
  }, [store]);

  // Save prompts to store when they change
  useEffect(() => {
    store.set('visualPrompt', visualPrompt);
  }, [visualPrompt, store]);

  useEffect(() => {
    store.set('subtitlePrompt', subtitlePrompt);
  }, [subtitlePrompt, store]);

  useEffect(() => {
    invoke('check_dependencies')
      .catch(err => {
        setError(err as string);
        console.error('Dependency check failed:', err);
      });
  }, []);

  return (
    <div className="min-h-screen bg-gray-100 py-8 px-4">
      <div className="max-w-2xl mx-auto bg-white rounded-lg shadow-md p-6">
        <div className="mb-8">
          <h1 className="text-2xl font-bold text-center">DeafBlind Video Assistant <span className="text-blue-500">1.0</span></h1>
        </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>
        )}

        {!selectedTask ? (
          <div className="space-y-6">
            <div className="flex justify-end mb-4">
              <button
                onClick={() => setIsSettingsOpen(true)}
                className="inline-flex items-center px-3 py-2 border border-transparent text-sm font-medium rounded-md text-gray-700 bg-gray-100 hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
              >
                <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
                Settings
              </button>
            </div>
            <h2 className="text-lg font-semibold text-center mb-8">Choose a Task</h2>
            <div className="grid grid-cols-2 gap-6">
              <button
                onClick={() => setSelectedTask('transcription')}
                className="flex flex-col items-center p-6 border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-colors"
              >
                <svg className="w-12 h-12 text-blue-500 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
                <span className="text-lg font-medium">Generate Transcription</span>
                <p className="text-sm text-gray-500 text-center mt-2">Create AI-powered descriptions for DeafBlind accessibility</p>
              </button>

              <button
                onClick={() => setSelectedTask('merge')}
                className="flex flex-col items-center p-6 border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-colors"
              >
                <svg className="w-12 h-12 text-blue-500 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 4v16M17 4v16M3 8h4m10 0h4M3 12h18M3 16h4m10 0h4M4 20h16a1 1 0 001-1V5a1 1 0 00-1-1H4a1 1 0 00-1 1v14a1 1 0 001 1z" />
                </svg>
                <span className="text-lg font-medium">Merge Subtitles</span>
                <p className="text-sm text-gray-500 text-center mt-2">Embed subtitle files into your video</p>
              </button>
            </div>
          </div>
        ) : (
          <div className="space-y-6">
            <div className="flex items-center mb-6">
              <button
                onClick={() => setSelectedTask(null)}
                className="inline-flex items-center text-gray-600 hover:text-gray-900"
              >
                <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                </svg>
                Back to Tasks
              </button>
            </div>

            {selectedTask === 'transcription' && (
              <TranscriptionTask
                apiKey={apiKey}
                visualPrompt={visualPrompt}
                subtitlePrompt={subtitlePrompt}
                onOpenSettings={() => setIsSettingsOpen(true)}
              />
            )}

            {selectedTask === 'merge' && (
              <MergeTask />
            )}
          </div>
        )}
      </div>

      <Settings
        isOpen={isSettingsOpen}
        onClose={() => setIsSettingsOpen(false)}
        apiKey={apiKey}
        onApiKeyChange={setApiKey}
        visualPrompt={visualPrompt}
        subtitlePrompt={subtitlePrompt}
        onVisualPromptChange={setVisualPrompt}
        onSubtitlePromptChange={setSubtitlePrompt}
      />
    </div>
  );
}

export default App;
