import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { cn } from '@/lib/utils'
import { useAuthStore } from '@/store/auth-store'
import { fetchFlashcardTerms, fetchUserProgress } from '../api/flashcard-api'
import type { FlashcardTerm, UserProgress } from '../api/flashcard-api'
import { resolveMediaUrl } from '../lib/media-url'

type FilterStatus = 'all' | 'new' | 'learning' | 'known' | 'ignored'

const STATUS_LABEL: Record<string, string> = {
  new: 'Mới',
  learning: 'Đang học',
  known: 'Đã biết',
  ignored: 'Bỏ qua',
}

const STATUS_CLASS: Record<string, string> = {
  new: 'at-chip',
  learning: 'at-chip at-chip-brand',
  known: 'at-chip at-chip-good',
  ignored: 'at-chip at-chip-warm',
}

interface Props {
  listId: number
}

export function FlashCardTermsPage({ listId }: Props) {
  const navigate = useNavigate()
  const user = useAuthStore(s => s.user)
  const [filter, setFilter] = useState<FilterStatus>('all')
  const [search, setSearch] = useState('')

  const { data: terms = [], isLoading: loadingTerms } = useQuery({
    queryKey: ['flashcard-terms', listId],
    queryFn: () => fetchFlashcardTerms(listId),
  })

  const { data: progress = [] } = useQuery({
    queryKey: ['flashcard-progress', user?.id, listId],
    queryFn: () => fetchUserProgress(user!.id, listId),
    enabled: !!user,
  })

  const progressMap: Record<number, UserProgress> = {}
  progress.forEach(p => { progressMap[p.term_id] = p })

  const getStatus = (termId: number): UserProgress['status'] =>
    progressMap[termId]?.status ?? 'new'

  const countAll = terms.length
  const countNew = terms.filter(t => getStatus(t.id) === 'new').length
  const countLearning = terms.filter(t => getStatus(t.id) === 'learning').length
  const countKnown = terms.filter(t => getStatus(t.id) === 'known').length

  const filtered = terms.filter(t => {
    if (filter !== 'all' && getStatus(t.id) !== filter) return false
    if (search.trim()) {
      const q = search.toLowerCase()
      return (
        t.word.toLowerCase().includes(q) ||
        (t.definition ?? '').toLowerCase().includes(q)
      )
    }
    return true
  })

  return (
    <div className="px-6 lg:px-10 py-10 page-enter">
      {/* Editorial head */}
      <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-6 mb-10">
        <div className="flex items-start gap-4 min-w-0">
          <button
            onClick={() => navigate({ to: '/flash-card' })}
            className="w-10 h-10 flex-shrink-0 grid place-items-center rounded-xl transition-colors hover:bg-[var(--at-line-2)]"
            style={{ color: 'var(--at-mute)' }}
          >
            <span className="material-symbols-outlined" style={{ fontSize: 22 }}>arrow_back</span>
          </button>
          <div className="min-w-0">
            <div className="at-eyebrow mb-2">Bộ thẻ từ vựng</div>
            <h1 className="at-title text-[32px] lg:text-4xl">
              {countAll} <i>từ</i>
            </h1>
          </div>
        </div>
        <button
          onClick={() => navigate({ to: '/flash-card/$listId/learn', params: { listId: String(listId) } })}
          className="inline-flex items-center gap-2 px-5 py-3 rounded-xl text-[13.5px] font-semibold transition-opacity hover:opacity-90"
          style={{ background: 'var(--at-ink)', color: 'var(--at-paper)' }}
        >
          <span className="material-symbols-outlined" style={{ fontSize: 16, fontVariationSettings: "'FILL' 1" }}>play_arrow</span>
          Bắt đầu học
        </button>
      </div>

      {/* Stats + filters */}
      <div
        className="rounded-2xl p-5 mb-6"
        style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}
      >
        <div className="flex flex-col md:flex-row md:items-center gap-4 justify-between mb-4">
          <div className="relative flex-1 max-w-sm">
            <span
              className="material-symbols-outlined absolute left-3.5 top-1/2 -translate-y-1/2"
              style={{ fontSize: 18, color: 'var(--at-mute)' }}
            >
              search
            </span>
            <input
              type="text"
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Tìm kiếm từ..."
              className="w-full pl-10 pr-4 py-2.5 rounded-full text-sm focus:outline-none"
              style={{
                background: 'var(--at-paper-2)',
                border: '1px solid var(--at-line)',
                color: 'var(--at-ink)',
              }}
            />
          </div>
          <div className="flex items-center gap-1.5 overflow-x-auto">
            {(['all', 'new', 'learning', 'known', 'ignored'] as FilterStatus[]).map(f => (
              <button
                key={f}
                onClick={() => setFilter(f)}
                className={cn(
                  'px-3.5 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-colors',
                )}
                style={{
                  background: filter === f ? 'var(--at-ink)' : 'var(--at-paper-2)',
                  color: filter === f ? 'var(--at-paper)' : 'var(--at-ink-2)',
                  border: '1px solid ' + (filter === f ? 'var(--at-ink)' : 'var(--at-line)'),
                }}
              >
                {f === 'all' ? 'Tất cả' : STATUS_LABEL[f]}
              </button>
            ))}
          </div>
        </div>
        <div className="grid grid-cols-4 gap-2">
          <HeadStat num={countAll} label="Tổng" />
          <HeadStat num={countNew} label="Mới" />
          <HeadStat num={countLearning} label="Đang học" color="var(--at-brand)" />
          <HeadStat num={countKnown} label="Đã biết" color="var(--at-good)" />
        </div>
      </div>

      {/* Terms list */}
      {loadingTerms ? (
        <div className="space-y-2">
          {Array.from({ length: 5 }).map((_, i) => (
            <div
              key={i}
              className="rounded-xl h-20 animate-pulse"
              style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}
            />
          ))}
        </div>
      ) : filtered.length === 0 ? (
        <div
          className="rounded-2xl p-12 text-center"
          style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}
        >
          <p className="text-sm" style={{ color: 'var(--at-mute)' }}>Không tìm thấy từ nào phù hợp.</p>
        </div>
      ) : (
        <div className="space-y-2">
          {filtered.map(term => (
            <TermRow key={term.id} term={term} status={getStatus(term.id)} />
          ))}
        </div>
      )}
    </div>
  )
}

function HeadStat({ num, label, color }: { num: number; label: string; color?: string }) {
  return (
    <div className="text-center py-2 rounded-lg" style={{ background: 'var(--at-paper-2)' }}>
      <div
        className="at-serif"
        style={{ fontSize: 22, fontWeight: 400, letterSpacing: '-0.02em', lineHeight: 1, color: color ?? 'var(--at-ink)' }}
      >
        {num}
      </div>
      <div
        className="mt-1"
        style={{ fontSize: 10, color: 'var(--at-mute)', textTransform: 'uppercase', letterSpacing: '0.12em', fontWeight: 600 }}
      >
        {label}
      </div>
    </div>
  )
}

function TermRow({ term, status }: { term: FlashcardTerm; status: UserProgress['status'] }) {
  const imageSrc = resolveMediaUrl(term.image_url)
  return (
    <div
      className="rounded-xl p-4 flex items-center gap-4 transition-shadow hover:shadow-sm"
      style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}
    >
      {imageSrc && (
        <img
          src={imageSrc}
          alt={term.word}
          loading="lazy"
          className="w-12 h-12 rounded-lg object-cover flex-shrink-0"
          style={{ background: 'var(--at-line-2)' }}
          onError={(e) => { (e.currentTarget as HTMLImageElement).style.display = 'none' }}
        />
      )}
      <div className="w-1/4 min-w-0">
        <div className="flex items-baseline gap-2 mb-1 flex-wrap">
          <h3
            className="at-serif text-[17px] tracking-tight truncate"
            style={{ color: 'var(--at-ink)', fontWeight: 500 }}
          >
            {term.word}
          </h3>
          {term.phonetic && (
            <span className="at-mono text-[11.5px] shrink-0" style={{ color: 'var(--at-mute)' }}>
              {term.phonetic}
            </span>
          )}
        </div>
        {term.part_of_speech && (
          <span
            className="at-serif italic"
            style={{ fontSize: 11, color: 'var(--at-mute-2)' }}
          >
            · {term.part_of_speech}
          </span>
        )}
      </div>
      <div className="flex-1 min-w-0 text-sm line-clamp-2" style={{ color: 'var(--at-ink-2)' }}>
        {term.definition ?? '—'}
      </div>
      <span className={STATUS_CLASS[status]}>
        <span className="at-chip-dot" />
        {STATUS_LABEL[status]}
      </span>
    </div>
  )
}
