import { useState, useEffect } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import api from '../api/client'

function StarRating({ rating, onRate, readonly = false }) {
  const [hover, setHover] = useState(0)
  return (
    <div style={{ display: 'inline-flex', gap: 2 }}>
      {[1, 2, 3, 4, 5].map(star => (
        <span key={star}
          onClick={readonly ? undefined : () => onRate(star)}
          onMouseEnter={readonly ? undefined : () => setHover(star)}
          onMouseLeave={readonly ? undefined : () => setHover(0)}
          style={{
            cursor: readonly ? 'default' : 'pointer', fontSize: '1.1rem',
            color: star <= (hover || rating) ? '#f59e0b' : 'var(--border)',
            transition: 'color 0.1s',
          }}>
          &#9733;
        </span>
      ))}
    </div>
  )
}

export default function FlashcardsPage() {
  const [tab, setTab] = useState('decks')
  const [decks, setDecks] = useState([])
  const [trashedDecks, setTrashedDecks] = useState([])
  const [sharedDecks, setSharedDecks] = useState([])
  const [sharedTotal, setSharedTotal] = useState(0)
  const [cards, setCards] = useState([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(true)
  const [searchQuery, setSearchQuery] = useState('')
  const [filterDeckId, setFilterDeckId] = useState('')
  const [studyCard, setStudyCard] = useState(null)
  const [flipped, setFlipped] = useState(false)
  const [editingDeckId, setEditingDeckId] = useState(null)
  const [editingTitle, setEditingTitle] = useState('')
  const [deletingCard, setDeletingCard] = useState(null)
  const { user } = useAuth()
  const navigate = useNavigate()
  const isAdmin = user?.role === 'admin'
  const LIMIT = 50
  const SHARED_LIMIT = 12

  const loadDecks = () => {
    api.get('/flashcards/').then(res => {
      setDecks(res.data)
      setLoading(false)
    }).catch(() => setLoading(false))
  }

  const loadTrash = () => {
    api.get('/flashcards/trash').then(res => setTrashedDecks(res.data)).catch(() => {})
  }

  const loadShared = (off = 0) => {
    api.get('/flashcards/shared', { params: { limit: SHARED_LIMIT, offset: off } }).then(res => {
      if (off === 0) setSharedDecks(res.data.decks)
      else setSharedDecks(prev => [...prev, ...res.data.decks])
      setSharedTotal(res.data.total)
    }).catch(() => {})
  }

  useEffect(() => { loadDecks() }, [])

  const loadCards = async (q = searchQuery, off = 0, deckId = filterDeckId) => {
    setLoading(true)
    try {
      const params = { limit: LIMIT, offset: off }
      if (q.trim()) params.q = q.trim()
      if (deckId) params.deck_id = parseInt(deckId)
      const res = await api.get('/flashcards/cards/browse', { params })
      setCards(off === 0 ? res.data.cards : prev => [...prev, ...res.data.cards])
      setTotal(res.data.total)
    } catch { } finally { setLoading(false) }
  }

  useEffect(() => {
    if (tab === 'browse') loadCards()
    if (tab === 'trash') loadTrash()
    if (tab === 'shared') loadShared(0)
  }, [tab])

  useEffect(() => {
    if (tab !== 'browse') return
    const t = setTimeout(() => loadCards(searchQuery, 0, filterDeckId), 300)
    return () => clearTimeout(t)
  }, [searchQuery, filterDeckId])

  const deleteDeck = async (deckId) => {
    try {
      await api.delete(`/flashcards/${deckId}`)
      setDecks(prev => prev.filter(d => d.id !== deckId))
    } catch { }
  }

  const permanentDeleteDeck = async (deckId) => {
    try {
      await api.delete(`/flashcards/${deckId}?permanent=true`)
      setTrashedDecks(prev => prev.filter(d => d.id !== deckId))
    } catch { }
  }

  const restoreDeck = async (deckId) => {
    try {
      await api.post(`/flashcards/${deckId}/restore`)
      setTrashedDecks(prev => prev.filter(d => d.id !== deckId))
      loadDecks()
    } catch { }
  }

  const saveTitle = async (deckId, newTitle) => {
    const t = (newTitle || '').trim()
    if (!t) return
    try {
      await api.patch(`/flashcards/${deckId}`, { title: t })
      setDecks(prev => prev.map(d => d.id === deckId ? { ...d, title: t } : d))
    } catch { }
  }

  const toggleShare = async (deckId) => {
    try {
      const res = await api.put(`/flashcards/${deckId}/share`)
      setDecks(prev => prev.map(d => d.id === deckId ? { ...d, is_shared: res.data.is_shared } : d))
    } catch { }
  }

  const adminUnshare = async (deckId) => {
    try {
      await api.delete(`/flashcards/${deckId}/share`)
      setSharedDecks(prev => prev.filter(d => d.id !== deckId))
      setSharedTotal(t => t - 1)
    } catch { }
  }

  const rateDeck = async (deckId, rating) => {
    try {
      const res = await api.post(`/flashcards/${deckId}/rate`, { rating })
      setSharedDecks(prev => prev.map(d => d.id === deckId
        ? { ...d, my_rating: res.data.my_rating, avg_rating: res.data.avg_rating, rating_count: res.data.rating_count }
        : d
      ))
    } catch { }
  }

  const deleteCard = async (cardId) => {
    try {
      await api.delete(`/flashcards/cards/${cardId}`)
      setCards(prev => prev.filter(c => c.id !== cardId))
      setTotal(t => t - 1)
      setDeletingCard(null)
    } catch { }
  }

  if (loading && decks.length === 0 && cards.length === 0) return <div className="loading"><div className="spinner" /></div>

  return (
    <div>
      <div className="card" style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
          <h2 style={{ marginBottom: 0 }}>Flashcards</h2>
          <div style={{ display: 'flex', gap: 4 }}>
            <button className={`btn btn-sm ${tab === 'decks' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setTab('decks')}>My Decks</button>
            <button className={`btn btn-sm ${tab === 'shared' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setTab('shared')}>Shared</button>
            <button className={`btn btn-sm ${tab === 'browse' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setTab('browse')}>Browse Cards</button>
            <button className={`btn btn-sm ${tab === 'trash' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setTab('trash')}>Trash</button>
          </div>
        </div>
      </div>

      {/* Study card modal */}
      {studyCard && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}
          onClick={e => e.target === e.currentTarget && (setStudyCard(null), setFlipped(false))}>
          <div style={{ background: 'var(--card-bg)', borderRadius: 'var(--card-radius)', padding: 32, maxWidth: 500, width: '100%', textAlign: 'center', boxShadow: '0 20px 60px rgba(0,0,0,0.3)', cursor: 'pointer', minHeight: 200, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}
            onClick={() => setFlipped(v => !v)}>
            <div style={{ fontSize: '0.72rem', color: 'var(--text-muted)', marginBottom: 12, textTransform: 'uppercase', fontWeight: 700 }}>
              {flipped ? 'Answer' : 'Question'} — tap to flip
            </div>
            <p style={{ fontSize: '1.1rem', lineHeight: 1.7 }}>
              {flipped ? studyCard.back : studyCard.front}
            </p>
            <div style={{ marginTop: 20, display: 'flex', gap: 8, justifyContent: 'center' }} onClick={e => e.stopPropagation()}>
              <button className="btn btn-secondary btn-sm" onClick={() => { setStudyCard(null); setFlipped(false) }}>Close</button>
            </div>
          </div>
        </div>
      )}

      {/* MY DECKS TAB */}
      {tab === 'decks' && (
        <>
          {decks.length === 0 && !loading && (
            <div className="card"><div className="empty-state">No flashcard decks yet. Create one from a document.</div></div>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
            {decks.map(deck => (
              <div key={deck.id} className="card" style={{ padding: 20 }}>
                {editingDeckId === deck.id ? (
                  <div style={{ marginBottom: 8 }}>
                    <input
                      type="text"
                      value={editingTitle}
                      onChange={e => setEditingTitle(e.target.value)}
                      onKeyDown={e => {
                        if (e.key === 'Enter') { saveTitle(deck.id, editingTitle); setEditingDeckId(null) }
                        if (e.key === 'Escape') setEditingDeckId(null)
                      }}
                      autoFocus
                      style={{ width: '100%', boxSizing: 'border-box', padding: '6px 10px', fontSize: '1rem', fontWeight: 600, border: '1px solid var(--border)', borderRadius: 6, background: 'var(--input-bg)', color: 'var(--text)', marginBottom: 8 }}
                    />
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                      <button className="btn btn-primary btn-sm" onClick={() => { saveTitle(deck.id, editingTitle); setEditingDeckId(null) }}>Save</button>
                      <button className="btn btn-secondary btn-sm" onClick={() => setEditingDeckId(null)}>Cancel</button>
                    </div>
                  </div>
                ) : (
                  <h3 style={{ fontSize: '1rem', marginBottom: 6, display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
                    <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{deck.title}</span>
                    <button
                      onClick={() => { setEditingDeckId(deck.id); setEditingTitle(deck.title) }}
                      title="Rename deck"
                      style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)', fontSize: '0.85rem', padding: '0 4px', flexShrink: 0 }}
                    >✎</button>
                  </h3>
                )}
                <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: 4 }}>
                  {deck.card_count} cards &middot; {new Date(deck.created_at).toLocaleDateString()}
                </p>
                {deck.is_shared ? (
                  <span style={{ fontSize: '0.72rem', padding: '2px 7px', borderRadius: 10, background: '#dbeafe', color: '#1d4ed8', fontWeight: 600 }}>Shared</span>
                ) : null}
                <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
                  <Link to={`/flashcards/${deck.id}/study`} className="btn btn-primary btn-sm">Study</Link>
                  <button className="btn btn-secondary btn-sm" onClick={() => toggleShare(deck.id)}>
                    {deck.is_shared ? 'Unshare' : 'Share'}
                  </button>
                  <button className="btn btn-danger btn-sm" onClick={() => deleteDeck(deck.id)}>Delete</button>
                </div>
              </div>
            ))}
          </div>
        </>
      )}

      {/* SHARED TAB */}
      {tab === 'shared' && (
        <>
          {sharedDecks.length === 0 && (
            <div className="card"><div className="empty-state">No shared decks yet.</div></div>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 12 }}>
            {sharedDecks.map(deck => (
              <div key={deck.id} className="card" style={{ padding: 20 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
                  <h3 style={{ fontSize: '1rem', marginBottom: 0 }}>{deck.title}</h3>
                  {isAdmin && (
                    <button className="btn btn-sm btn-secondary" onClick={() => adminUnshare(deck.id)}
                      style={{ fontSize: '0.7rem', padding: '2px 6px' }} title="Remove from shared">
                      Unshare
                    </button>
                  )}
                </div>
                <p style={{ color: 'var(--text-muted)', fontSize: '0.82rem', marginBottom: 6 }}>
                  by {deck.owner_name} · {deck.card_count} cards
                </p>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                  <StarRating rating={deck.my_rating || 0} onRate={(r) => rateDeck(deck.id, r)} />
                  <span style={{ fontSize: '0.78rem', color: 'var(--text-muted)' }}>
                    {deck.avg_rating > 0 ? `${deck.avg_rating}` : 'No ratings'}{deck.rating_count > 0 ? ` (${deck.rating_count})` : ''}
                  </span>
                </div>
                <Link to={`/flashcards/${deck.id}/study`} className="btn btn-primary btn-sm">Study</Link>
              </div>
            ))}
          </div>
          {sharedDecks.length < sharedTotal && (
            <div style={{ textAlign: 'center', marginTop: 16 }}>
              <button className="btn btn-secondary" onClick={() => loadShared(sharedDecks.length)}>
                Load more ({sharedTotal - sharedDecks.length} remaining)
              </button>
            </div>
          )}
        </>
      )}

      {/* BROWSE TAB */}
      {tab === 'browse' && (
        <>
          <div style={{ display: 'flex', gap: 8, marginBottom: 12, flexWrap: 'wrap', alignItems: 'center' }}>
            <div style={{ flex: 1, minWidth: 200 }}>
              <input type="text" placeholder="Search cards..." value={searchQuery} onChange={e => setSearchQuery(e.target.value)}
                style={{ width: '100%', padding: '9px 13px', border: '1px solid var(--border)', borderRadius: 8, fontSize: '0.9rem', background: 'var(--input-bg)', color: 'var(--text)' }} />
            </div>
            <select value={filterDeckId} onChange={e => setFilterDeckId(e.target.value)}
              style={{ padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 8, fontSize: '0.85rem', background: 'var(--input-bg)', color: 'var(--text)' }}>
              <option value="">All decks</option>
              {decks.map(d => <option key={d.id} value={d.id}>{d.title} ({d.card_count})</option>)}
            </select>
          </div>

          <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: 12 }}>{total} cards</p>

          {cards.map(card => (
            <div key={card.id} style={{
              background: 'var(--card-bg)', border: '1px solid var(--border)',
              borderRadius: 'var(--card-radius)', padding: '14px 16px', marginBottom: 8,
              display: 'flex', gap: 10, alignItems: 'flex-start',
            }}>
              <div style={{ flex: 1, cursor: 'pointer' }} onClick={() => { setStudyCard(card); setFlipped(false) }}>
                <div style={{ fontSize: '0.72rem', color: 'var(--text-muted)', marginBottom: 4 }}>{card.deck_title}</div>
                <p style={{ fontSize: '0.9rem', fontWeight: 600, marginBottom: 4 }}>{card.front}</p>
                <p style={{ fontSize: '0.82rem', color: 'var(--text-muted)' }}>{card.back.slice(0, 120)}{card.back.length > 120 ? '...' : ''}</p>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4, flexShrink: 0 }}>
                <button className="btn btn-sm btn-secondary" onClick={() => { setStudyCard(card); setFlipped(false) }}>View</button>
                {deletingCard === card.id ? (
                  <div style={{ display: 'flex', gap: 4 }}>
                    <button className="btn btn-sm btn-danger" onClick={() => deleteCard(card.id)}>Yes</button>
                    <button className="btn btn-sm btn-secondary" onClick={() => setDeletingCard(null)}>No</button>
                  </div>
                ) : (
                  <button className="btn btn-sm btn-secondary" onClick={() => setDeletingCard(card.id)}
                    style={{ fontSize: '0.72rem', color: 'var(--text-muted)' }}>Delete</button>
                )}
              </div>
            </div>
          ))}

          {!loading && cards.length === 0 && (
            <div className="card"><div className="empty-state">No cards found.</div></div>
          )}

          {cards.length < total && (
            <div style={{ textAlign: 'center', marginTop: 12 }}>
              <button className="btn btn-secondary" onClick={() => loadCards(searchQuery, cards.length, filterDeckId)} disabled={loading}>
                {loading ? 'Loading...' : `Load more (${total - cards.length} remaining)`}
              </button>
            </div>
          )}
        </>
      )}

      {/* TRASH TAB */}
      {tab === 'trash' && (
        <>
          {trashedDecks.length === 0 && (
            <div className="card"><div className="empty-state">Trash is empty.</div></div>
          )}
          {trashedDecks.map(deck => (
            <div key={deck.id} className="card" style={{ padding: '14px 16px', marginBottom: 8, opacity: 0.7 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
                <div>
                  <strong>{deck.title}</strong>
                  <div style={{ fontSize: '0.82rem', color: 'var(--text-muted)' }}>
                    {deck.card_count} cards · Deleted {new Date(deck.deleted_at).toLocaleDateString()}
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <button className="btn btn-primary btn-sm" onClick={() => restoreDeck(deck.id)}>Restore</button>
                  <button className="btn btn-danger btn-sm" onClick={() => permanentDeleteDeck(deck.id)}>Delete forever</button>
                </div>
              </div>
            </div>
          ))}
        </>
      )}
    </div>
  )
}
