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

export default function OverdueReport() {
  const [data, setData]       = useState([])
  const [loading, setLoading] = useState(true)

  const load = async () => {
    setLoading(true)
    try { setData(await borrowApi.overdueReport()) }
    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 urgency = days => {
    if (days >= 30) return { label: 'Critical', color: '#e05c5c', bg: 'rgba(224,92,92,0.15)' }
    if (days >= 14) return { label: 'High',     color: '#e08045', bg: 'rgba(224,128,69,0.15)' }
    return              { label: 'Medium',   color: 'var(--amber)', bg: 'rgba(232,160,69,0.12)' }
  }

  return (
    <div>
      <div className="page-header">
        <div>
          <h1 className="page-title" style={{ color: 'var(--red)' }}>Overdue Report</h1>
          <p className="page-subtitle">
            All currently active borrow records past their due date.
            {data.length > 0 && <> Running this report also marks them as <strong style={{ color: 'var(--red)' }}>Overdue</strong> in the database.</>}
          </p>
        </div>
        <button className="btn btn-secondary" onClick={load}>Refresh</button>
      </div>

      {/* Summary bar */}
      {!loading && data.length > 0 && (
        <div style={{ display: 'flex', gap: 16, marginBottom: 28 }}>
          {[
            { label: 'Total Overdue',  value: data.length,                                   color: 'var(--red)' },
            { label: 'Critical (30d+)', value: data.filter(r => r.daysOverdue >= 30).length, color: '#e05c5c' },
            { label: 'High (14–29d)',  value: data.filter(r => r.daysOverdue >= 14 && r.daysOverdue < 30).length, color: '#e08045' },
            { label: 'Avg Days Over', value: Math.round(data.reduce((s, r) => s + r.daysOverdue, 0) / data.length), color: 'var(--amber)' },
          ].map(s => (
            <div key={s.label} className="stat-card" style={{ flex: 1 }}>
              <div className="stat-value" style={{ color: s.color }}>{s.value}</div>
              <div className="stat-label">{s.label}</div>
            </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 }}>
          <div style={{ fontSize: '2.5rem', marginBottom: 12 }}>✅</div>
          <h3 style={{ fontFamily: 'var(--font-display)', marginBottom: 8, color: 'var(--green)' }}>All clear!</h3>
          <p style={{ color: 'var(--text-muted)' }}>No overdue borrow records at this time.</p>
        </div>
      ) : (
        <div className="table-wrapper">
          <table>
            <thead>
              <tr>
                <th>Borrower</th>
                <th>Book</th>
                <th>Author</th>
                <th>Genre</th>
                <th>Borrowed</th>
                <th>Due Date</th>
                <th>Days Overdue</th>
                <th>Urgency</th>
              </tr>
            </thead>
            <tbody>
              {data.map(r => {
                const u = urgency(r.daysOverdue)
                return (
                  <tr key={r.borrowRecordId} style={{ background: 'rgba(224,92,92,0.03)' }}>
                    <td>
                      <div className="td-primary">{r.borrowerName}</div>
                      <div style={{ fontSize: '0.78rem', color: 'var(--text-muted)' }}>{r.borrowerEmail}</div>
                    </td>
                    <td className="td-primary">{r.bookTitle}</td>
                    <td>{r.authorFullName}</td>
                    <td>
                      {r.genre
                        ? <span className="badge badge-genre">{r.genre}</span>
                        : <span className="text-muted">—</span>
                      }
                    </td>
                    <td>{fmt(r.borrowDate)}</td>
                    <td style={{ color: 'var(--red)', fontWeight: 600 }}>{fmt(r.dueDate)}</td>
                    <td style={{ color: 'var(--red)', fontWeight: 700, fontFamily: 'var(--font-display)', fontSize: '1.1rem' }}>
                      {r.daysOverdue}
                    </td>
                    <td>
                      <span className="badge" style={{ background: u.bg, color: u.color }}>
                        {u.label}
                      </span>
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}
