'use client'

import React, { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { useTheme } from '@/lib/ThemeContext'
import { AudioButton } from '@/components/learn/AudioButton'

function getApiBase() {
  return ''  // Same-origin proxy
}

export default function StoryPage() {
  const { unitId } = useParams<{ unitId: string }>()
  const router = useRouter()
  const { isDark } = useTheme()

  const [story, setStory] = useState<{ story_html: string; story_text: string; vocab_used: string[]; language: string } | null>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [language, setLanguage] = useState<'en' | 'de'>('en')

  const glassCard = isDark
    ? 'bg-white/10 backdrop-blur-xl border border-white/10'
    : 'bg-white/80 backdrop-blur-xl border border-black/5'

  const generateStory = async () => {
    setIsLoading(true)
    setError(null)

    try {
      // First get the QA data to extract vocabulary
      const qaResp = await fetch(`${getApiBase()}/api/learning-units/${unitId}/qa`)
      let vocabulary: { english: string; german: string }[] = []

      if (qaResp.ok) {
        const qaData = await qaResp.json()
        // Convert QA items to vocabulary format
        vocabulary = (qaData.qa_items || []).map((item: any) => ({
          english: item.question,
          german: item.answer,
        }))
      }

      if (vocabulary.length === 0) {
        setError('Keine Vokabeln gefunden.')
        setIsLoading(false)
        return
      }

      // Generate story
      const resp = await fetch(`${getApiBase()}/api/learning-units/${unitId}/generate-story`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ vocabulary, language, grade_level: '5-8' }),
      })

      if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
      const data = await resp.json()
      setStory(data)
    } catch (err: any) {
      setError(err.message)
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <>
      {/* Header */}
      <div className={`${glassCard} border-0 border-b`}>
        <div className="max-w-2xl mx-auto px-6 py-4 flex items-center justify-between">
          <button
            onClick={() => router.push('/learn')}
            className={`flex items-center gap-2 text-sm ${isDark ? 'text-white/60 hover:text-white' : 'text-slate-500 hover:text-slate-900'}`}
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
            Zurueck
          </button>
          <h1 className={`text-lg font-bold ${isDark ? 'text-white' : 'text-slate-900'}`}>
            Minigeschichte
          </h1>
          <button
            onClick={() => setLanguage((l) => l === 'en' ? 'de' : 'en')}
            className={`text-xs px-3 py-1.5 rounded-lg ${isDark ? 'bg-white/10 text-white/70' : 'bg-slate-100 text-slate-600'}`}
          >
            {language === 'en' ? 'Englisch' : 'Deutsch'}
          </button>
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 flex items-center justify-center px-6 py-8">
        <div className="w-full max-w-lg space-y-6">
          {story ? (
            <>
              {/* Story Card */}
              <div className={`${glassCard} rounded-3xl p-8`}>
                <div className="flex items-center justify-between mb-4">
                  <span className={`text-xs font-medium uppercase ${isDark ? 'text-white/40' : 'text-slate-400'}`}>
                    {story.language === 'en' ? 'English Story' : 'Deutsche Geschichte'}
                  </span>
                  <AudioButton text={story.story_text} lang={story.language as 'en' | 'de'} isDark={isDark} size="md" />
                </div>
                <div
                  className={`text-lg leading-relaxed ${isDark ? 'text-white/90' : 'text-slate-800'}`}
                  dangerouslySetInnerHTML={{ __html: story.story_html }}
                />
                <style>{`
                  .vocab-highlight {
                    background: ${isDark ? 'rgba(96, 165, 250, 0.3)' : 'rgba(59, 130, 246, 0.15)'};
                    color: ${isDark ? '#93c5fd' : '#1d4ed8'};
                    padding: 1px 4px;
                    border-radius: 4px;
                    font-weight: 600;
                  }
                `}</style>
              </div>

              {/* Vocab used */}
              <div className={`text-center text-sm ${isDark ? 'text-white/40' : 'text-slate-400'}`}>
                Vokabeln verwendet: {story.vocab_used.length} / {story.vocab_used.length > 0 ? story.vocab_used.join(', ') : '-'}
              </div>

              {/* New Story Button */}
              <button
                onClick={generateStory}
                disabled={isLoading}
                className="w-full py-3 rounded-xl bg-gradient-to-r from-amber-500 to-orange-500 text-white font-medium hover:shadow-lg transition-all"
              >
                Neue Geschichte generieren
              </button>
            </>
          ) : (
            <div className={`${glassCard} rounded-3xl p-10 text-center`}>
              <div className="text-5xl mb-4">📖</div>
              <h2 className={`text-xl font-bold mb-2 ${isDark ? 'text-white' : 'text-slate-900'}`}>
                Minigeschichte
              </h2>
              <p className={`text-sm mb-6 ${isDark ? 'text-white/60' : 'text-slate-500'}`}>
                Die KI schreibt eine kurze Geschichte mit deinen Vokabeln.
                Die Vokabelwoerter werden farbig hervorgehoben.
              </p>

              {error && (
                <p className={`text-sm mb-4 ${isDark ? 'text-red-300' : 'text-red-600'}`}>{error}</p>
              )}

              <button
                onClick={generateStory}
                disabled={isLoading}
                className={`w-full py-4 rounded-xl font-medium transition-all ${
                  isLoading
                    ? (isDark ? 'bg-white/5 text-white/30' : 'bg-slate-100 text-slate-400')
                    : 'bg-gradient-to-r from-amber-500 to-orange-500 text-white hover:shadow-lg hover:shadow-orange-500/25'
                }`}
              >
                {isLoading ? (
                  <span className="flex items-center justify-center gap-3">
                    <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    Geschichte wird geschrieben...
                  </span>
                ) : (
                  'Geschichte generieren'
                )}
              </button>
            </div>
          )}
        </div>
      </div>
    </>
  )
}
