// components/admin/Dashboard.jsx
function Dashboard() {
  const [stats, setStats] = React.useState(null);
  const [mancanti, setMancanti] = React.useState(null); // null = chiuso, [] = caricando/lista

  React.useEffect(() => {
    api('/report/sommario').then(setStats);
  }, []);

  async function vediMancanti() {
    setMancanti([]);
    const data = await api('/report/mancanti');
    setMancanti(data || []);
  }

  if (!stats) return <div className="spinner" />;

  const cards = [
    { label:'Alunni attivi',   value: stats.alunni,       color:'var(--accent)' },
    { label:'Prestiti totali', value: stats.prestiti,     color:'var(--ink)' },
    { label:'Consegnati',      value: stats.consegnati,   color:'var(--green)' },
    { label:'Restituiti',      value: stats.restituiti,   color:'var(--orange)' },
    { label:'Mancanti',        value: stats.mancanti,     color:'var(--red)', action: vediMancanti },
    { label:'Quote pagate',    value: `${stats.quote_pagate}/${stats.quote_totali}`, color:'var(--ink)' },
  ];

  return (
    <div>
      <div className="page-header">
        <h1 className="page-title">Dashboard</h1>
        <span style={{ fontSize:'.85rem', color:'var(--ink2)' }}>Anno {stats.anno}</span>
      </div>
      <div className="stat-grid">
        {cards.map(c => (
          <div className={`stat-card ${c.action ? 'clickable' : ''}`} key={c.label} onClick={c.action} style={c.action ? { cursor:'pointer', border:'1px solid var(--red)', background:'var(--red-bg)' } : {}}>
            <div className="label">{c.label}</div>
            <div className="value" style={{ color: c.color }}>{c.value}</div>
            {c.action && <div style={{ fontSize:'.7rem', marginTop:'.25rem', fontWeight:600 }}>Clicca per dettagli →</div>}
          </div>
        ))}
      </div>

      {mancanti && (
        <div className="modal-backdrop" onClick={() => setMancanti(null)}>
          <div className="modal" style={{ maxWidth: 800, width: '90vw' }} onClick={e => e.stopPropagation()}>
            <div className="modal-title">Libri da restituire ({mancanti.length})</div>
            <div style={{ maxHeight: '60vh', overflowY: 'auto' }}>
              {mancanti.length === 0 ? (
                <div style={{ padding: '2rem', textAlign: 'center', color: 'var(--ink2)' }}>Caricamento o nessun libro mancante...</div>
              ) : (
                <table className="tbl">
                  <thead>
                    <tr>
                      <th>Alunno</th>
                      <th>Classe</th>
                      <th>Libro</th>
                      <th>Codice</th>
                      <th>Consegnato</th>
                    </tr>
                  </thead>
                  <tbody>
                    {mancanti.map(m => (
                      <tr key={m.id}>
                        <td style={{ fontWeight: 600 }}>{m.cognome} {m.nome}</td>
                        <td>{m.classe_nome}</td>
                        <td>{m.titolo}</td>
                        <td className="mono">{m.codice_interno}</td>
                        <td>{new Date(m.data_consegna).toLocaleDateString('it')}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
            <div className="modal-footer">
              <button className="btn btn-primary" onClick={() => setMancanti(null)}>Chiudi</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
