import { useQuery } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { fetchFlashcardLists } from '../api/flashcard-api'
import { useAuthStore } from '@/store/auth-store'
import { fetchUserProgress } from '../api/flashcard-api'
import type { FlashcardList } from '../api/flashcard-api'

function ListCard({ list, userId }: { list: FlashcardList; userId: string | null }) {
  const navigate = useNavigate()

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

  const countLearning = progress.filter(p => p.status === 'learning').length
  const countKnown = progress.filter(p => p.status === 'known').length
  const progressPct = list.total_words > 0
    ? Math.round(((countLearning + countKnown) / list.total_words) * 100)
    : 0

  return (
    <div
      className="rounded-2xl p-6 flex flex-col transition-all hover:-translate-y-1"
      style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}
    >
      <div className="flex justify-between items-start mb-4">
        <div className="flex items-center gap-3">
          <div
            className="w-11 h-11 rounded-xl grid place-items-center flex-shrink-0 at-serif italic"
            style={{ background: 'var(--at-ink)', color: 'var(--at-paper)', fontSize: 18, fontWeight: 500 }}
          >
            {list.title.charAt(0).toUpperCase()}
          </div>
          <div className="min-w-0">
            <h3
              className="at-serif text-[17px] leading-[1.2] tracking-tight line-clamp-2"
              style={{ color: 'var(--at-ink)', fontWeight: 500 }}
            >
              {list.title}
            </h3>
            <div className="flex items-center gap-1.5 mt-1">
              <span className="material-symbols-outlined" style={{ fontSize: 13, color: 'var(--at-mute)' }}>book</span>
              <span className="text-xs font-medium" style={{ color: 'var(--at-mute)' }}>
                {list.total_words} từ
              </span>
            </div>
          </div>
        </div>
        <span className={`at-chip ${list.is_public ? 'at-chip-brand' : ''}`}>
          <span className="at-chip-dot" />
          {list.is_public ? 'Công khai' : 'Riêng tư'}
        </span>
      </div>

      {list.description && (
        <p className="text-xs leading-[1.5] mb-4 line-clamp-2" style={{ color: 'var(--at-mute)' }}>
          {list.description}
        </p>
      )}

      <div className="mt-2 mb-4">
        <div className="flex justify-between items-baseline mb-2">
          <span className="at-eyebrow" style={{ fontSize: 10 }}>Tiến độ</span>
          <span
            className="at-serif italic"
            style={{ fontSize: 18, color: 'var(--at-brand)', letterSpacing: '-0.02em', lineHeight: 1 }}
          >
            {progressPct}%
          </span>
        </div>
        <div className="at-bar">
          <span style={{ width: `${progressPct}%` }} />
        </div>
      </div>

      <div className="grid grid-cols-3 gap-2 mb-5">
        <Stat num={list.total_words - countLearning - countKnown} label="Mới" />
        <Stat num={countLearning} label="Học" color="var(--at-brand)" />
        <Stat num={countKnown} label="Biết" color="var(--at-good)" />
      </div>

      <div className="grid grid-cols-2 gap-2 mt-auto">
        <button
          onClick={() => navigate({ to: '/flash-card/$listId', params: { listId: String(list.id) } })}
          className="py-2.5 rounded-xl text-[13px] font-semibold transition-colors"
          style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)', color: 'var(--at-ink-2)' }}
        >
          Xem thẻ
        </button>
        <button
          onClick={() => navigate({ to: '/flash-card/$listId/learn', params: { listId: String(list.id) } })}
          className="py-2.5 rounded-xl text-[13px] font-semibold transition-opacity hover:opacity-90"
          style={{ background: 'var(--at-ink)', color: 'var(--at-paper)' }}
        >
          Học ngay
        </button>
      </div>
    </div>
  )
}

function Stat({ num, label, color }: { num: number; label: string; color?: string }) {
  return (
    <div className="text-center py-1.5 rounded-lg" style={{ background: 'var(--at-paper-2)' }}>
      <div
        className="at-serif"
        style={{ fontSize: 20, fontWeight: 400, letterSpacing: '-0.02em', lineHeight: 1, color: color ?? 'var(--at-ink)' }}
      >
        {num}
      </div>
      <div className="text-[10px] font-semibold mt-1 tracking-wider uppercase" style={{ color: 'var(--at-mute)' }}>
        {label}
      </div>
    </div>
  )
}

export function FlashCardListPage() {
  const user = useAuthStore(s => s.user)
  const { data: lists = [], isLoading, isError } = useQuery({
    queryKey: ['flashcard-lists'],
    queryFn: fetchFlashcardLists,
  })

  return (
    <div className="px-6 lg:px-10 py-10 page-enter">
      <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-6 mb-10">
        <div>
          <div className="at-eyebrow mb-3">Từ vựng TOEIC</div>
          <h1 className="at-title text-4xl lg:text-[44px]">
            Bộ thẻ <i>ghi nhớ</i>
          </h1>
          <p className="mt-4 text-sm" style={{ color: 'var(--at-mute)' }}>
            Chọn bộ thẻ để bắt đầu — {lists.length} bộ sưu tầm
          </p>
        </div>
      </div>

      {isLoading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
          {Array.from({ length: 6 }).map((_, i) => (
            <div
              key={i}
              className="rounded-2xl p-6 h-64 animate-pulse"
              style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}
            />
          ))}
        </div>
      ) : isError ? (
        <div
          className="rounded-2xl p-10 text-center"
          style={{ background: 'var(--at-bad-soft)', border: '1px solid rgba(193,68,62,0.2)' }}
        >
          <p className="text-sm" style={{ color: 'var(--at-bad)' }}>
            Không thể tải danh sách bộ thẻ. Vui lòng thử lại.
          </p>
        </div>
      ) : lists.length === 0 ? (
        <div
          className="rounded-2xl p-16 text-center"
          style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}
        >
          <span className="material-symbols-outlined mb-3 block" style={{ fontSize: 48, color: 'var(--at-mute-2)' }}>library_books</span>
          <p className="at-serif text-lg" style={{ color: 'var(--at-ink)' }}>Chưa có bộ thẻ nào.</p>
          <p className="text-sm mt-1" style={{ color: 'var(--at-mute)' }}>Bộ thẻ từ vựng TOEIC sẽ được thêm sớm!</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
          {lists.map(list => (
            <ListCard key={list.id} list={list} userId={user?.id ?? null} />
          ))}
        </div>
      )}
    </div>
  )
}
