import { useState, useCallback } from 'react'
import { useWebSpeechTranscription } from './hooks/useWebSpeechTranscription'
import { useWhisperTranscription } from './hooks/useWhisperTranscription'
import './App.css'

type TranscriptionMode = 'webspeech' | 'whisper'

function App() {
  const [mode, setMode] = useState<TranscriptionMode>('webspeech')
  const [transcript, setTranscript] = useState('')
  const [error, setError] = useState<string | null>(null)
  const [modelProgress, setModelProgress] = useState<{ progress: number; status: string } | null>(null)
  const [recordingTime, setRecordingTime] = useState(0)
  const [timerInterval, setTimerInterval] = useState<NodeJS.Timeout | null>(null)

  // Web Speech API hook
  const webSpeech = useWebSpeechTranscription({
    onTranscriptUpdate: (text) => {
      setTranscript(prev => prev + (prev ? ' ' : '') + text)
    },
    onError: (err) => setError(err.message),
    language: 'en-US'
  })

  // Whisper hook
  const whisper = useWhisperTranscription({
    onTranscriptUpdate: (text) => {
      setTranscript(prev => prev + (prev ? ' ' : '') + text)
    },
    onError: (err) => setError(err.message),
    onModelProgress: (progress, status) => setModelProgress({ progress, status }),
    language: 'en'
  })

  const isRecording = mode === 'webspeech' ? webSpeech.isRecording : whisper.isRecording
  const isSupported = mode === 'webspeech' ? webSpeech.isSupported : true

  // Start timer
  const startTimer = useCallback(() => {
    setRecordingTime(0)
    const interval = setInterval(() => {
      setRecordingTime(prev => prev + 1)
    }, 1000)
    setTimerInterval(interval)
  }, [])

  // Stop timer
  const stopTimer = useCallback(() => {
    if (timerInterval) {
      clearInterval(timerInterval)
      setTimerInterval(null)
    }
  }, [timerInterval])

  // Handle start recording
  const handleStart = useCallback(async () => {
    setError(null)
    startTimer()

    if (mode === 'webspeech') {
      webSpeech.startRecording()
    } else {
      await whisper.startRecording()
    }
  }, [mode, webSpeech, whisper, startTimer])

  // Handle stop recording
  const handleStop = useCallback(async () => {
    stopTimer()

    if (mode === 'webspeech') {
      webSpeech.stopRecording()
    } else {
      await whisper.stopRecording()
    }
  }, [mode, webSpeech, whisper, stopTimer])

  // Handle clear
  const handleClear = useCallback(() => {
    setTranscript('')
    setRecordingTime(0)
    if (mode === 'webspeech') {
      webSpeech.clearTranscript()
    } else {
      whisper.clearTranscript()
    }
  }, [mode, webSpeech, whisper])

  // Copy to clipboard
  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(transcript)
      // Show brief feedback
      const btn = document.querySelector('.copy-btn') as HTMLButtonElement
      if (btn) {
        const originalText = btn.textContent
        btn.textContent = 'Copied!'
        setTimeout(() => {
          btn.textContent = originalText
        }, 1500)
      }
    } catch (err) {
      console.error('Failed to copy:', err)
    }
  }, [transcript])

  // Download as text file
  const handleDownload = useCallback(() => {
    const blob = new Blob([transcript], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `transcript-${new Date().toISOString().slice(0, 10)}.txt`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }, [transcript])

  // Format recording time
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}:${secs.toString().padStart(2, '0')}`
  }

  return (
    <div className="app">
      <header className="header">
        <h1>Transcribe</h1>
        <p className="subtitle">Voice to text, right in your browser</p>
      </header>

      <main className="main">
        {/* Mode selector */}
        <div className="mode-selector">
          <button
            className={`mode-btn ${mode === 'webspeech' ? 'active' : ''}`}
            onClick={() => setMode('webspeech')}
            disabled={isRecording}
          >
            Web Speech
            <span className="mode-desc">Fast, requires internet</span>
          </button>
          <button
            className={`mode-btn ${mode === 'whisper' ? 'active' : ''}`}
            onClick={() => setMode('whisper')}
            disabled={isRecording}
          >
            Whisper
            <span className="mode-desc">Local AI, works offline</span>
          </button>
        </div>

        {/* Model loading status for Whisper */}
        {mode === 'whisper' && !whisper.modelLoaded && (
          <div className="model-status">
            {whisper.modelLoading ? (
              <>
                <div className="progress-bar">
                  <div
                    className="progress-fill"
                    style={{ width: `${modelProgress?.progress || 0}%` }}
                  />
                </div>
                <p className="progress-text">{modelProgress?.status || 'Loading model...'}</p>
              </>
            ) : (
              <p className="model-info">
                Model will be downloaded on first use (~75MB)
              </p>
            )}
          </div>
        )}

        {/* Error display */}
        {error && (
          <div className="error-banner">
            <span>{error}</span>
            <button onClick={() => setError(null)}>×</button>
          </div>
        )}

        {/* Recording controls */}
        <div className="controls">
          {!isRecording ? (
            <button
              className="record-btn start"
              onClick={handleStart}
              disabled={!isSupported || (mode === 'whisper' && whisper.modelLoading)}
            >
              <svg viewBox="0 0 24 24" width="32" height="32" fill="currentColor">
                <circle cx="12" cy="12" r="10" />
              </svg>
              <span>Start Recording</span>
            </button>
          ) : (
            <button className="record-btn stop" onClick={handleStop}>
              <svg viewBox="0 0 24 24" width="32" height="32" fill="currentColor">
                <rect x="6" y="6" width="12" height="12" rx="2" />
              </svg>
              <span>Stop Recording</span>
            </button>
          )}

          {isRecording && (
            <div className="recording-indicator">
              <span className="pulse" />
              <span className="time">{formatTime(recordingTime)}</span>
            </div>
          )}
        </div>

        {/* Transcript display */}
        <div className="transcript-container">
          <div className="transcript-header">
            <h2>Transcript</h2>
            {transcript && (
              <div className="transcript-actions">
                <button className="action-btn copy-btn" onClick={handleCopy}>
                  Copy
                </button>
                <button className="action-btn" onClick={handleDownload}>
                  Download
                </button>
                <button className="action-btn clear-btn" onClick={handleClear}>
                  Clear
                </button>
              </div>
            )}
          </div>

          <div className="transcript-box">
            {transcript ? (
              <p className="transcript-text">{transcript}</p>
            ) : (
              <p className="transcript-placeholder">
                {isRecording ? 'Listening...' : 'Your transcript will appear here'}
              </p>
            )}

            {/* Interim text for Web Speech */}
            {mode === 'webspeech' && webSpeech.interimTranscript && (
              <p className="interim-text">{webSpeech.interimTranscript}</p>
            )}

            {/* Transcribing indicator for Whisper */}
            {mode === 'whisper' && whisper.isTranscribing && (
              <p className="transcribing-indicator">Processing audio...</p>
            )}
          </div>
        </div>
      </main>

      <footer className="footer">
        <p>
          {mode === 'webspeech'
            ? 'Using browser\'s built-in speech recognition'
            : 'Using local Whisper AI model'}
        </p>
      </footer>
    </div>
  )
}

export default App
