import { useState } from 'react'
import { cn } from '@/lib/utils'
import { FlashCard } from './FlashCard'
import { useVocabStore } from '@/store/vocab-store'
import { useVocab } from '@/hooks/use-vocab'
import { VOCAB_TOPICS } from '@/types'
import type { VocabTopic, VocabWord } from '@/types'
import { useRequireAuth } from '@/hooks/use-require-auth'

const GUEST_CARD_LIMIT = 5

export function Vocabulary() {
  const { currentTopic, currentIndex, knownWords, setTopic, setCurrentIndex, markKnown, markNeedReview } = useVocabStore()
  const [isFlipped, setIsFlipped] = useState(false)
  const { isAuthenticated, requireAuth } = useRequireAuth()

  const { data: allVocab = [], isLoading, isError } = useVocab()
  const filtered: VocabWord[] = currentTopic === 'Tất cả'
    ? allVocab
    : allVocab.filter((w) => w.topic === currentTopic)
  const safeIndex = Math.min(currentIndex, Math.max(0, filtered.length - 1))
  const word = filtered[safeIndex]
  const knownInFiltered = filtered.filter((w) => knownWords.includes(w.id)).length

  function handleSetTopic(topic: VocabTopic) {
    setTopic(topic)
    setCurrentIndex(0)
    setIsFlipped(false)
  }

  function handlePrev() {
    if (safeIndex > 0) {
      setCurrentIndex(safeIndex - 1)
      setIsFlipped(false)
    }
  }

  function handleNext() {
    if (safeIndex < filtered.length - 1) {
      if (!isAuthenticated && safeIndex >= GUEST_CARD_LIMIT - 1) {
        requireAuth()
        return
      }
      setCurrentIndex(safeIndex + 1)
      setIsFlipped(false)
    }
  }

  function handleMarkKnown() {
    if (!isAuthenticated && safeIndex >= GUEST_CARD_LIMIT - 1) {
      requireAuth()
      return
    }
    if (word) markKnown(word.id)
    handleNext()
  }

  function handleMarkReview() {
    if (!isAuthenticated && safeIndex >= GUEST_CARD_LIMIT - 1) {
      requireAuth()
      return
    }
    if (word) markNeedReview(word.id)
    handleNext()
  }

  const recentKnown = knownWords
    .map((id) => allVocab.find((w) => w.id === id))
    .filter((w): w is VocabWord => w !== undefined)
    .slice(-5)
    .reverse()

  return (
    <div className="px-4 lg:px-6 py-6 page-enter">
      {/* Mobile topic chips */}
      <div className="lg:hidden mb-4 overflow-x-auto pb-1">
        <div className="flex gap-2 w-max">
          {VOCAB_TOPICS.map((topic) => (
            <button
              key={topic}
              onClick={() => handleSetTopic(topic)}
              className={cn(
                'px-4 py-2 rounded-full text-sm font-semibold whitespace-nowrap transition-colors',
                currentTopic === topic
                  ? 'bg-blue-600 text-white'
                  : 'bg-white border border-slate-200 text-slate-600 hover:border-blue-300',
              )}
            >
              {topic}
            </button>
          ))}
        </div>
      </div>

      <div className="flex gap-5">
        {/* Left: Topic menu — desktop only */}
        <div className="hidden lg:block w-44 flex-shrink-0">
          <div className="bg-white rounded-2xl border border-slate-200 p-3 sticky top-20">
            <div className="text-xs text-slate-400 font-semibold uppercase tracking-wider px-2 mb-2">Chủ đề</div>
            {VOCAB_TOPICS.map((topic) => (
              <button
                key={topic}
                onClick={() => handleSetTopic(topic)}
                className={cn(
                  'w-full text-left px-3 py-2.5 rounded-xl text-sm font-medium transition-colors',
                  currentTopic === topic
                    ? 'bg-blue-50 text-blue-600 font-semibold'
                    : 'text-slate-600 hover:bg-slate-50',
                )}
              >
                {topic}
              </button>
            ))}
          </div>
        </div>

        {/* Center: Flashcard */}
        <div className="flex-1 min-w-0">
          {isLoading ? (
            <div className="bg-white rounded-2xl border border-slate-200 p-10 flex flex-col items-center justify-center gap-3">
              <div className="w-8 h-8 border-2 border-blue-100 border-t-blue-600 rounded-full animate-spin" />
              <p className="text-sm text-slate-400">Đang tải từ vựng...</p>
            </div>
          ) : isError ? (
            <div className="bg-red-50 rounded-2xl border border-red-100 p-10 text-center">
              <p className="text-sm text-red-500">Không thể tải từ vựng. Vui lòng thử lại.</p>
            </div>
          ) : filtered.length === 0 ? (
            <div className="bg-white rounded-2xl border border-slate-200 p-10 text-center">
              <p className="text-slate-400">Không có từ vựng cho chủ đề này.</p>
            </div>
          ) : (
            <>
              {/* Progress */}
              <div className="flex items-center justify-between mb-3">
                <span className="text-xs text-slate-400 font-medium">
                  {safeIndex + 1} / {filtered.length} từ
                </span>
                <span className="text-xs font-semibold text-blue-600">
                  {knownInFiltered}/{filtered.length} đã thuộc
                </span>
              </div>
              <div className="h-1.5 w-full rounded-full bg-slate-200 mb-4">
                <div
                  className="h-full bg-blue-600 rounded-full transition-all duration-300"
                  style={{ width: `${filtered.length > 0 ? ((safeIndex + 1) / filtered.length) * 100 : 0}%` }}
                />
              </div>

              {word && (
                <FlashCard
                  word={word.word}
                  phonetic={word.phonetic}
                  meaningVi={word.meaningVi}
                  example={word.example}
                  topicBadge={word.topic}
                  isFlipped={isFlipped}
                  onFlip={() => setIsFlipped((v) => !v)}
                />
              )}

              {/* Navigation */}
              <div className="flex items-center justify-between mt-4">
                <button
                  onClick={handlePrev}
                  disabled={safeIndex === 0}
                  className="flex items-center gap-1.5 px-4 py-2.5 border border-slate-200 rounded-xl text-sm font-semibold text-slate-600 hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                >
                  <span className="material-symbols-outlined" style={{ fontSize: 18 }}>chevron_left</span>
                  Trước
                </button>

                <div className="flex gap-2">
                  <button
                    onClick={handleMarkReview}
                    className="flex items-center gap-1.5 px-4 py-2.5 border border-amber-200 bg-amber-50 text-amber-700 rounded-xl text-sm font-semibold hover:bg-amber-100 transition-colors"
                  >
                    <span className="material-symbols-outlined" style={{ fontSize: 16 }}>replay</span>
                    <span className="hidden sm:inline">Cần ôn</span>
                  </button>
                  <button
                    onClick={handleMarkKnown}
                    className="flex items-center gap-1.5 px-4 py-2.5 border border-green-200 bg-green-50 text-green-700 rounded-xl text-sm font-semibold hover:bg-green-100 transition-colors"
                  >
                    <span className="material-symbols-outlined" style={{ fontSize: 16 }}>check</span>
                    <span className="hidden sm:inline">Đã thuộc</span>
                  </button>
                </div>

                <button
                  onClick={handleNext}
                  disabled={safeIndex === filtered.length - 1}
                  className="flex items-center gap-1.5 px-4 py-2.5 border border-slate-200 rounded-xl text-sm font-semibold text-slate-600 hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                >
                  Tiếp
                  <span className="material-symbols-outlined" style={{ fontSize: 18 }}>chevron_right</span>
                </button>
              </div>
            </>
          )}
        </div>

        {/* Right: Stats — desktop only */}
        <div className="hidden lg:flex flex-col gap-4 w-52 flex-shrink-0">
          <div className="bg-white rounded-2xl border border-slate-200 p-4">
            <div className="text-xs text-slate-400 font-semibold uppercase tracking-wider mb-3">Thống kê</div>
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-xs text-slate-500">Đã xem</span>
                <span className="text-sm font-bold text-slate-800">{safeIndex + 1}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-xs text-slate-500">Đã thuộc</span>
                <span className="text-sm font-bold text-green-600">{knownWords.length}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-xs text-slate-500">Tổng từ</span>
                <span className="text-sm font-bold text-blue-600">{allVocab.length}</span>
              </div>
            </div>
            <div className="mt-3 pt-3 border-t border-slate-100">
              <div className="flex items-center gap-1.5">
                <span className="material-symbols-outlined text-amber-500" style={{ fontSize: 16 }}>local_fire_department</span>
                <span className="text-xs text-slate-500">Streak hôm nay</span>
              </div>
              <div className="text-2xl font-extrabold text-amber-500 mt-1">{Math.min(safeIndex + 1, 99)}</div>
            </div>
          </div>

          {recentKnown.length > 0 && (
            <div className="bg-white rounded-2xl border border-slate-200 p-4">
              <div className="text-xs text-slate-400 font-semibold uppercase tracking-wider mb-3">Vừa thuộc</div>
              <div className="space-y-2">
                {recentKnown.map((w) => w && (
                  <div key={w.id} className="flex items-center gap-2">
                    <span className="w-1.5 h-1.5 rounded-full bg-green-400 flex-shrink-0" />
                    <span className="text-sm font-semibold text-slate-700 truncate">{w.word}</span>
                    <span className="text-xs text-slate-400 truncate ml-auto">{w.meaningVi}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
