import { useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import { authorsApi } from '../api/client'

export default function TopBorrowed() {
  const [data, setData]     = useState([])
  const [loading, setLoading] = useState(true)
  const [topN, setTopN]     = useState(5)

  const load = async () => {
    setLoading(true)
    try { setData(await authorsApi.topBorrowed(topN)) }
    catch (e) { toast.error(e.message) }
    finally { setLoading(false) }
  }

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

  const fmt = d => d ? new Date(d).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }) : '—'

  const max = data[0]?.totalBorrows || 1

  return (
    <div>
      <div className="page-header">
        <div>
          <h1 className="page-title">Top Borrowed Authors</h1>
          <p className="page-subtitle">Authors ranked by total number of borrow events across all their books</p>
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <label style={{ fontSize: '0.85rem', color: 'var(--text-muted)' }}>Show top</label>
          <select
            className="filter-select"
            value={topN}
            onChange={e => setTopN(Number(e.target.value))}
            style={{ minWidth: 70 }}
          >
            {[3,5,10,20].map(n => <option key={n} value={n}>{n}</option>)}
          </select>
          <button className="btn btn-primary" onClick={load}>Refresh</button>
        </div>
      </div>

      {loading ? (
        <div style={{ textAlign: 'center', padding: 64, color: 'var(--text-muted)', fontStyle: 'italic' }}>Loading…</div>
      ) : data.length === 0 ? (
        <div className="card" style={{ textAlign: 'center', padding: 64 }}>
          <p style={{ color: 'var(--text-muted)' }}>No borrow data available yet. Create some borrow records first.</p>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {data.map((author, i) => (
            <div key={author.authorId} className="card" style={{ display: 'flex', alignItems: 'center', gap: 24, padding: '20px 28px' }}>
              {/* Rank badge */}
              <div style={{
                width: 44, height: 44, borderRadius: '50%', flexShrink: 0,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                background: i === 0 ? 'var(--amber)' : i === 1 ? 'rgba(232,160,69,0.3)' : 'var(--bg-elevated)',
                color: i === 0 ? '#0f1117' : 'var(--text-primary)',
                fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: '1.1rem'
              }}>
                {i + 1}
              </div>

              {/* Info */}
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: '1.1rem', fontWeight: 600, color: 'var(--text-primary)', marginBottom: 2 }}>
                  {author.fullName}
                </div>
                <div style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>
                  {author.nationality && <span style={{ marginRight: 12 }}>📍 {author.nationality}</span>}
                  <span>Last borrowed: {fmt(author.lastBorrowDate)}</span>
                </div>

                {/* Progress bar */}
                <div style={{ marginTop: 10, height: 6, background: 'var(--bg-elevated)', borderRadius: 3, overflow: 'hidden' }}>
                  <div style={{
                    height: '100%', borderRadius: 3,
                    width: `${(author.totalBorrows / max) * 100}%`,
                    background: i === 0 ? 'var(--amber)' : 'rgba(232,160,69,0.4)',
                    transition: 'width 0.5s ease'
                  }} />
                </div>
              </div>

              {/* Stats */}
              <div style={{ display: 'flex', gap: 28, flexShrink: 0 }}>
                <Metric value={author.totalBorrows} label="Total Borrows" highlight={i === 0} />
                <Metric value={author.uniqueBooks} label="Unique Books" />
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

function Metric({ value, label, highlight }) {
  return (
    <div style={{ textAlign: 'center' }}>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: '1.6rem', fontWeight: 700, color: highlight ? 'var(--amber)' : 'var(--text-primary)', lineHeight: 1 }}>
        {value}
      </div>
      <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.08em', marginTop: 4 }}>
        {label}
      </div>
    </div>
  )
}
