/* ============ Reports ============ */

function Reports() {
  const { clients, signings, mileage, settings } = useStore();
  const year = new Date().getFullYear();
  const toast = useToast();
  // Re-render when backups change
  const [, setBackupTick] = React.useState(0);
  React.useEffect(() => Store.subscribe(() => setBackupTick(t => t+1)), []);
  const backups = Store.listBackups();

  // Annual summary
  const yearStart = `${year}-01-01`;
  const yearSignings = signings.filter(s => s.date >= yearStart && s.status === 'Completed');
  const yearMileage  = mileage.filter(m => m.date >= yearStart);
  const grossRevenue = yearSignings.reduce((s,x) => s + (parseFloat(x.fee)||0), 0)
                     + clients.filter(c => c.paid).reduce((s,c) => s + (parseFloat(c.revenue)||0), 0);
  const totalMiles   = yearMileage.reduce((s,m) => s + (parseFloat(m.miles)||0) * (m.roundTrip ? 2 : 1), 0);
  const deduction    = totalMiles * (settings.mileageRate||0);
  const netIncome    = grossRevenue - deduction;

  // Monthly breakdown
  const months = [];
  for (let i = 0; i < 12; i++) {
    const d = new Date(year, i, 1);
    months.push({ key: d.toISOString().slice(0,7), label: d.toLocaleDateString('en-US', { month: 'short' }) });
  }
  const monthly = months.map(mo => {
    const monthSignings = yearSignings.filter(s => s.date.startsWith(mo.key));
    const monthMileage = yearMileage.filter(m => m.date.startsWith(mo.key));
    const rev = monthSignings.reduce((s,x) => s + (parseFloat(x.fee)||0), 0);
    const miles = monthMileage.reduce((s,m) => s + (parseFloat(m.miles)||0) * (m.roundTrip ? 2 : 1), 0);
    return { ...mo, signings: monthSignings.length, revenue: rev, miles, deduction: miles * (settings.mileageRate||0) };
  });

  const exportClients = () => {
    const rows = [
      ['ID','Name','Phone','Email','Source','Status','Priority','Revenue','Paid','Notes'],
      ...clients.map(c => [c.id, c.name, c.phone, c.email, c.source, c.status, c.priority, c.revenue, c.paid ? 'Yes' : 'No', c.notes||''])
    ];
    downloadCSV('clients', rows);
  };
  const exportSignings = () => {
    const rows = [
      ['ID','Date','Time','Title','Client','DocType','Location','DurationMin','Fee','Status','Notes'],
      ...signings.map(s => {
        const client = clients.find(c => c.id === s.clientId);
        return [s.id, s.date, s.time, s.title, client?.name || '', s.docType, s.location, s.durationMin, s.fee, s.status, s.notes||''];
      })
    ];
    downloadCSV('signings', rows);
  };
  const exportAll = () => {
    const blob = new Blob([JSON.stringify({ clients, signings, mileage, settings }, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = `notary-studio-backup-${todayISO()}.json`; a.click();
    URL.revokeObjectURL(url);
  };

  const importAll = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      try {
        const payload = JSON.parse(reader.result);
        if (confirm('Replace ALL current data with the imported file? This cannot be undone.')) {
          Store.importJSON(payload);
        }
      } catch(err) { alert('Could not parse file: ' + err.message); }
    };
    reader.readAsText(file);
    e.target.value = '';
  };

  return (
    <div>
      <div className="stat-grid" style={{ marginBottom: 18 }}>
        <Stat label={`Gross revenue · ${year}`} value={fmt.money(grossRevenue)} delta={`${yearSignings.length} completed signings`} iconName="money" iconColor="var(--green)" />
        <Stat label="Mileage deduction"        value={fmt.money(deduction)}    delta={`${totalMiles.toFixed(0)} mi @ $${settings.mileageRate.toFixed(3)}/mi`} iconName="car" iconColor="var(--purple)" />
        <Stat label="Net (rev − mileage)"      value={fmt.money(netIncome)}    delta="Before other expenses" iconName="chart" iconColor="var(--blue)" />
        <Stat label="Active clients"           value={clients.length}          delta={`${clients.filter(c => !c.paid).length} with balance`} iconName="people" iconColor="var(--orange)" />
      </div>

      <Card title={`Monthly breakdown · ${year}`} sub="Completed signings and tracked mileage by month">
        <div style={{ overflowX: 'auto', margin: '-4px -4px' }}>
          <table className="list">
            <thead>
              <tr>
                <th>Month</th>
                <th className="num">Signings</th>
                <th className="num">Revenue</th>
                <th className="num">Miles</th>
                <th className="num">Deduction</th>
                <th className="num">Net</th>
              </tr>
            </thead>
            <tbody>
              {monthly.map(mo => (
                <tr key={mo.key}>
                  <td style={{ fontWeight: 500 }}>{mo.label} {year}</td>
                  <td className="num mono">{mo.signings}</td>
                  <td className="num mono">{fmt.money(mo.revenue)}</td>
                  <td className="num mono">{mo.miles.toFixed(1)}</td>
                  <td className="num mono" style={{ color: 'var(--purple)' }}>{fmt.money(mo.deduction, 2)}</td>
                  <td className="num mono" style={{ fontWeight: 600 }}>{fmt.money(mo.revenue - mo.deduction)}</td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr style={{ background: 'var(--surface-2)', fontWeight: 600 }}>
                <td style={{ padding: '10px 12px' }}>Year total</td>
                <td className="num mono" style={{ padding: '10px 12px' }}>{yearSignings.length}</td>
                <td className="num mono" style={{ padding: '10px 12px' }}>{fmt.money(grossRevenue)}</td>
                <td className="num mono" style={{ padding: '10px 12px' }}>{totalMiles.toFixed(1)}</td>
                <td className="num mono" style={{ padding: '10px 12px', color: 'var(--purple)' }}>{fmt.money(deduction)}</td>
                <td className="num mono" style={{ padding: '10px 12px', color: 'var(--green)' }}>{fmt.money(netIncome)}</td>
              </tr>
            </tfoot>
          </table>
        </div>
      </Card>

      <div style={{ height: 14 }}></div>

      <Card title="Exports & backup" sub="Take your data anywhere. Stored on this device.">
        <div className="row" style={{ flexWrap: 'wrap', gap: 8 }}>
          <Button variant="bordered" icon="download" onClick={exportClients}>Export clients (CSV)</Button>
          <Button variant="bordered" icon="download" onClick={exportSignings}>Export signings (CSV)</Button>
          <Button variant="bordered" icon="download" onClick={() => exportMileageCSV(mileage, clients, settings)}>Export mileage (CSV)</Button>
          <div className="grow"></div>
          <Button variant="primary" icon="download" onClick={exportAll}>Backup everything (JSON)</Button>
          <label className="btn bordered" style={{ cursor: 'pointer' }}>
            <Icon name="upload" size={14}/> Restore from backup…
            <input type="file" accept=".json,application/json" onChange={importAll} style={{ display: 'none' }}/>
          </label>
        </div>
      </Card>

      <div style={{ height: 14 }}></div>

      <Card title="Automatic backups" sub={`Snapshots taken daily and on tab close. Last ${backups.length} kept on this device.`}
        action={<Button variant="tinted" icon="plus" onClick={() => { Store.snapshotNow('Manual snapshot'); toast('Snapshot saved'); }}>Snapshot now</Button>}>
        {backups.length === 0 ? (
          <Empty icon="file" title="No snapshots yet" hint="Snapshots are taken automatically — check back tomorrow, or take one manually." />
        ) : (
          <div style={{ overflowX: 'auto', margin: '-4px -4px' }}>
            <table className="list">
              <thead>
                <tr>
                  <th>Snapshot</th>
                  <th>Taken</th>
                  <th className="num">Clients</th>
                  <th className="num">Signings</th>
                  <th className="num">Trips</th>
                  <th className="col-action"></th>
                </tr>
              </thead>
              <tbody>
                {backups.map(b => (
                  <tr key={b.id}>
                    <td>
                      <div style={{ fontWeight: 500 }}>{b.label || (b.date === todayISO() ? 'Today' : fmt.date(b.date))}</div>
                      <div className="mono" style={{ fontSize: 11, color: 'var(--text-3)' }}>{b.id}</div>
                    </td>
                    <td>
                      <div style={{ fontSize: 13 }}>{new Date(b.createdAt).toLocaleString('en-US', { month:'short', day:'numeric', hour:'numeric', minute:'2-digit' })}</div>
                      <div className="mono" style={{ fontSize: 11, color: 'var(--text-3)' }}>{fmt.relativeTime(new Date(b.createdAt).getTime())}</div>
                    </td>
                    <td className="num mono">{b.counts?.clients ?? '—'}</td>
                    <td className="num mono">{b.counts?.signings ?? '—'}</td>
                    <td className="num mono">{b.counts?.mileage ?? '—'}</td>
                    <td className="col-action">
                      <div className="row" style={{ gap: 4, justifyContent: 'flex-end' }}>
                        <IconButton name="download" title="Download as JSON" onClick={() => downloadBackup(b)} />
                        <IconButton name="upload" title="Restore" onClick={() => {
                          if (confirm(`Restore snapshot from ${fmt.date(b.date)}? Your current data will be replaced.`)) {
                            // Take a safety snapshot first so this restore is itself undoable
                            Store.snapshotNow('Before restore — ' + new Date().toLocaleString());
                            Store.restoreBackup(b.id);
                            toast('Restored from ' + fmt.date(b.date));
                          }
                        }} />
                        <IconButton name="trash" title="Delete snapshot" onClick={() => {
                          if (confirm('Delete this snapshot?')) { Store.deleteBackup(b.id); toast('Snapshot deleted'); }
                        }} />
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        <div className="muted" style={{ fontSize: 12, marginTop: 10, lineHeight: 1.5 }}>
          Snapshots are stored on this device only. For off-device safety, click <b>Backup everything (JSON)</b> above and keep the file in cloud storage.
        </div>
      </Card>
    </div>
  );
}

window.Reports = Reports;

function downloadBackup(b) {
  const blob = new Blob([JSON.stringify(b.data, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `notary-studio-${b.date}-${b.id.slice(-6)}.json`;
  a.click();
  URL.revokeObjectURL(url);
}
