/* ============ Mileage ============ */

function Mileage({ search }) {
  const { mileage, clients, settings } = useStore();
  const [editing, setEditing] = React.useState(null);
  const [range, setRange] = React.useState('all'); // all | mtd | ytd

  const today = new Date();
  const rangeStart = React.useMemo(() => {
    if (range === 'mtd') return new Date(today.getFullYear(), today.getMonth(), 1).toISOString().slice(0,10);
    if (range === 'ytd') return new Date(today.getFullYear(), 0, 1).toISOString().slice(0,10);
    return '0000-01-01';
  }, [range]);

  const filtered = React.useMemo(() => {
    const q = (search || '').toLowerCase().trim();
    return [...mileage]
      .filter(m => m.date >= rangeStart)
      .filter(m => {
        if (!q) return true;
        const client = clients.find(c => c.id === m.clientId);
        const hay = `${m.purpose} ${m.from} ${m.to} ${client?.name || ''}`.toLowerCase();
        return hay.includes(q);
      })
      .sort((a,b) => b.date.localeCompare(a.date) || (b.createdAt||'').localeCompare(a.createdAt||''));
  }, [mileage, clients, rangeStart, search]);

  const tripMiles = (m) => (parseFloat(m.miles)||0) * (m.roundTrip ? 2 : 1);
  const totalMiles = filtered.reduce((s,m) => s + tripMiles(m), 0);
  const totalDeduction = totalMiles * (settings.mileageRate || 0);
  const tripCount = filtered.length;
  const avgPerTrip = tripCount ? totalMiles / tripCount : 0;

  return (
    <div>
      <div className="stat-grid" style={{ marginBottom: 18 }}>
        <Stat label="Total miles" value={totalMiles.toFixed(1)} delta={`${tripCount} trip${tripCount === 1 ? '' : 's'}`} iconName="car" iconColor="var(--purple)" />
        <Stat label="Tax deduction" value={fmt.money(totalDeduction, 2)} delta={`@ $${settings.mileageRate.toFixed(3)}/mi`} iconName="money" iconColor="var(--green)" />
        <Stat label="Avg per trip" value={avgPerTrip.toFixed(1) + ' mi'} delta="Per logged entry" iconName="chart" iconColor="var(--blue)" />
        <Stat label="Round trips" value={filtered.filter(m => m.roundTrip).length} delta={`of ${tripCount} entries`} iconName="arrowRt" iconColor="var(--orange)" />
      </div>

      <div className="row" style={{ marginBottom: 14 }}>
        <Segmented value={range} onChange={setRange} options={[
          { value: 'mtd', label: 'This month' },
          { value: 'ytd', label: 'Year to date' },
          { value: 'all', label: 'All time' },
        ]}/>
        <div className="grow"></div>
        <Button icon="download" onClick={() => exportMileageCSV(filtered, clients, settings)}>Export CSV</Button>
        <Button variant="primary" icon="plus" onClick={() => setEditing({ _new: true })}>Log trip</Button>
      </div>

      <div className="card" style={{ overflow: 'hidden' }}>
        {filtered.length === 0 ? (
          <Empty icon="car" title="No trips logged yet" hint="Log every drive to a signing — the deduction adds up fast." action={<Button variant="primary" icon="plus" onClick={() => setEditing({ _new: true })}>Log trip</Button>} />
        ) : (
        <div style={{ overflowX: 'auto' }}>
          <table className="list">
            <thead>
              <tr>
                <th className="col-num">№</th>
                <th>Date</th>
                <th>Purpose</th>
                <th>From → To</th>
                <th>Client</th>
                <th className="num">Miles</th>
                <th>R/T</th>
                <th className="num">Deduction</th>
                <th className="col-action"></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((m, i) => {
                const client = clients.find(c => c.id === m.clientId);
                const miles = tripMiles(m);
                const ded = miles * (settings.mileageRate || 0);
                return (
                  <tr key={m.id} style={{ cursor: 'pointer' }} onClick={() => setEditing(m)}>
                    <td className="col-num">{String(i+1).padStart(2,'0')}</td>
                    <td className="nowrap"><span style={{ fontWeight: 500 }}>{fmt.dateShort(m.date)}</span></td>
                    <td>{m.purpose || <span className="muted">—</span>}</td>
                    <td style={{ fontSize: 12.5, color: 'var(--text-2)' }}>
                      <span>{m.from || '—'}</span>
                      <Icon name="arrowRt" size={11} color="var(--text-4)" />
                      <span style={{ marginLeft: 6 }}>{m.to || '—'}</span>
                    </td>
                    <td>
                      {client ? <span style={{ fontWeight: 500 }}>{client.name}</span> : <span className="muted">—</span>}
                    </td>
                    <td className="num mono">{miles.toFixed(1)}</td>
                    <td>{m.roundTrip ? <Pill tone="blue">R/T</Pill> : <Pill tone="gray">One-way</Pill>}</td>
                    <td className="num mono" style={{ fontWeight: 600, color: 'var(--text)' }}>{fmt.money(ded, 2)}</td>
                    <td className="col-action"><IconButton name="edit" /></td>
                  </tr>
                );
              })}
            </tbody>
            <tfoot>
              <tr style={{ background: 'var(--surface-2)', fontWeight: 600 }}>
                <td colSpan="5" style={{ padding: '10px 12px', textAlign: 'right', color: 'var(--text-3)', textTransform: 'uppercase', fontSize: 11, letterSpacing: '0.04em' }}>Totals</td>
                <td className="num mono" style={{ padding: '10px 12px' }}>{totalMiles.toFixed(1)}</td>
                <td></td>
                <td className="num mono" style={{ padding: '10px 12px', color: 'var(--green)' }}>{fmt.money(totalDeduction, 2)}</td>
                <td></td>
              </tr>
            </tfoot>
          </table>
        </div>
        )}
      </div>

      {editing && <MileageEditor draft={editing} clients={clients} settings={settings} onClose={() => setEditing(null)} />}
    </div>
  );
}

function MileageEditor({ draft, clients, settings, onClose }) {
  const isNew = !!draft._new;
  const [m, setM] = React.useState(isNew ? {
    date: todayISO(), clientId: null, purpose: '', from: settings.baseAddress || 'Office', to: '',
    miles: 0, roundTrip: true, notes: '',
  } : draft);
  const toast = useToast();
  const set = (patch) => setM(prev => ({ ...prev, ...patch }));

  const totalMiles = (parseFloat(m.miles)||0) * (m.roundTrip ? 2 : 1);
  const deduction = totalMiles * (settings.mileageRate || 0);

  const save = () => {
    if (isNew) { Store.Mileage.add(m); toast('Trip logged'); }
    else { Store.Mileage.update(draft.id, m); toast('Trip updated'); }
    onClose();
  };
  const del = () => {
    if (confirm('Delete this trip?')) { Store.Mileage.remove(draft.id); toast('Trip deleted'); onClose(); }
  };

  return (
    <Modal title={isNew ? 'Log trip' : 'Edit trip'} onClose={onClose}
      footer={<>
        {!isNew && <Button variant="danger" icon="trash" onClick={del}>Delete</Button>}
        <div className="grow"></div>
        <Button onClick={onClose}>Cancel</Button>
        <Button variant="primary" onClick={save}>{isNew ? 'Log trip' : 'Save'}</Button>
      </>}>
      <div className="field-row">
        <Field label="Date"><Input type="date" value={m.date} onChange={e => set({ date: e.target.value })}/></Field>
        <Field label="Linked client">
          <Select value={m.clientId || ''} onChange={e => set({ clientId: e.target.value || null })}>
            <option value="">— None —</option>
            {clients.map(c => <option key={c.id} value={c.id}>{c.name || '(unnamed)'}</option>)}
          </Select>
        </Field>
      </div>
      <Field label="Purpose"><Input value={m.purpose} onChange={e => set({ purpose: e.target.value })} placeholder="Loan signing, courthouse run…"/></Field>
      <div className="field-row">
        <Field label="From"><Input value={m.from} onChange={e => set({ from: e.target.value })} placeholder="Office"/></Field>
        <Field label="To"><Input value={m.to} onChange={e => set({ to: e.target.value })} placeholder="Client address"/></Field>
      </div>
      <div className="field-row">
        <Field label="One-way miles"><Input type="number" step="0.1" value={m.miles} onChange={e => set({ miles: parseFloat(e.target.value)||0 })}/></Field>
        <Field label="Trip type">
          <Segmented value={m.roundTrip ? 'rt' : 'ow'} onChange={v => set({ roundTrip: v === 'rt' })} options={[
            { value: 'rt', label: 'Round trip' },
            { value: 'ow', label: 'One-way' },
          ]}/>
        </Field>
      </div>
      <div style={{ background: 'var(--surface-3)', borderRadius: 10, padding: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <div style={{ fontSize: 11, color: 'var(--text-3)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>Total distance</div>
          <div className="mono" style={{ fontSize: 20, fontWeight: 600 }}>{totalMiles.toFixed(1)} mi</div>
        </div>
        <div style={{ width: 1, height: 36, background: 'var(--line)' }}></div>
        <div>
          <div style={{ fontSize: 11, color: 'var(--text-3)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>Tax deduction</div>
          <div className="mono" style={{ fontSize: 20, fontWeight: 600, color: 'var(--green)' }}>{fmt.money(deduction, 2)}</div>
        </div>
      </div>
      <Field label="Notes"><Textarea value={m.notes||''} onChange={e => set({ notes: e.target.value })} placeholder="Optional"/></Field>
    </Modal>
  );
}

function exportMileageCSV(list, clients, settings) {
  const headers = ['Date','Purpose','From','To','OneWayMiles','RoundTrip','TotalMiles','Deduction','Client','Notes'];
  const rows = list.map(m => {
    const client = clients.find(c => c.id === m.clientId);
    const total = (parseFloat(m.miles)||0) * (m.roundTrip ? 2 : 1);
    const ded = total * (settings.mileageRate||0);
    return [m.date, m.purpose, m.from, m.to, m.miles, m.roundTrip ? 'Yes' : 'No', total.toFixed(1), ded.toFixed(2), client?.name || '', m.notes];
  });
  downloadCSV('mileage', [headers, ...rows]);
}

function downloadCSV(name, rows) {
  const csv = rows.map(r => r.map(v => `"${String(v ?? '').replace(/"/g,'""')}"`).join(',')).join('\n');
  const blob = new Blob([csv], { type: 'text/csv' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = `${name}-${todayISO()}.csv`; a.click();
  URL.revokeObjectURL(url);
}

window.Mileage = Mileage;
window.exportMileageCSV = exportMileageCSV;
window.downloadCSV = downloadCSV;
