// Reservasi — manage upcoming reservations + waitlist
const { useState: useStateRS } = React;

function ReservasiPage({ pushToast }) {
  const [view, setView] = useStateRS('today'); // today | week
  const [showForm, setShowForm] = useStateRS(false);

  // Derive status from time
  const enriched = RESERVATIONS.map(r => {
    const [h, m] = r.time.split(':').map(Number);
    const [nh, nm] = NOW_HHMM.split(':').map(Number);
    const reservMin = h*60 + m;
    const nowMin = nh*60 + nm;
    const diff = reservMin - nowMin;
    let status = 'upcoming';
    if (diff < -30) status = 'no-show';
    else if (diff < 0) status = 'arrived';
    else if (diff < 60) status = 'soon';
    return { ...r, status, diff };
  });

  const upcoming = enriched.filter(r => r.status === 'upcoming' || r.status === 'soon');
  const arrived = enriched.filter(r => r.status === 'arrived');

  return (
    <>
      <PageHeader
        eyebrow={`${formatDateID(TODAY)} · ${enriched.length} reservasi terjadwal`}
        title="Reservasi"
        subtitle="Kelola booking meja, walk-in waitlist, dan no-show. Tamu otomatis di-notif via WhatsApp 1 jam sebelum waktu reservasi."
        actions={<>
          <Btn icon="calendar">Kalender</Btn>
          <Btn tone="primary" icon="plus" onClick={() => setShowForm(true)}>Reservasi Baru</Btn>
        </>}
      />

      <div className="grid-4 mb-4">
        <Kpi label="Total Hari Ini" value={enriched.length + ' booking'} icon="calendar" tone="accent" />
        <Kpi label="Upcoming" value={upcoming.length} icon="clock" tone="warn"
             hint={upcoming.length > 0 ? `Berikutnya jam ${upcoming[0]?.time}` : 'Tidak ada'} />
        <Kpi label="Sudah Datang" value={arrived.length} icon="check" tone="success" />
        <Kpi label="Total Tamu" value={enriched.reduce((s,r)=>s+r.guests, 0) + ' orang'} icon="users" tone="muted" />
      </div>

      <div className="filter-bar">
        <button className={'menu-cat-tab' + (view==='today'?' active':'')} onClick={()=>setView('today')}>Hari Ini</button>
        <button className={'menu-cat-tab' + (view==='week'?' active':'')} onClick={()=>setView('week')}>Minggu Ini</button>
        <input className="filter-search" placeholder="Cari nama tamu / nomor HP…" />
        <select>
          <option>Semua status</option>
          <option>Upcoming</option>
          <option>Arrived</option>
          <option>No-show</option>
        </select>
      </div>

      {showForm && (
        <Card className="mb-4" style={{borderColor:'hsl(var(--accent-h) var(--accent-s) 70%)', borderWidth:2}}>
          <div className="card-header">
            <h3 className="card-title">Form Reservasi Baru</h3>
            <button className="btn ghost sm" onClick={() => setShowForm(false)}><Icon name="x" size={14}/></button>
          </div>
          <div className="card-body">
            <div className="grid-2" style={{gap:14}}>
              <div className="field">
                <label>Nama Tamu</label>
                <input className="input" placeholder="Contoh: Pak Budi" />
              </div>
              <div className="field">
                <label>Nomor HP / WA</label>
                <input className="input" placeholder="0812xxxx" />
              </div>
              <div className="field">
                <label>Tanggal & Waktu</label>
                <input className="input" type="datetime-local" defaultValue="2026-04-22T18:00" />
              </div>
              <div className="field">
                <label>Jumlah Tamu</label>
                <input className="input" type="number" min={1} defaultValue={2} />
              </div>
              <div className="field">
                <label>Meja Pilihan</label>
                <select className="select">
                  <option>Auto-assign</option>
                  {TABLES.filter(t => t.zone !== 'bar').map(t => <option key={t.id}>{t.label} · {t.zone} · {t.seats} seats</option>)}
                </select>
              </div>
              <div className="field">
                <label>Zona Preferensi</label>
                <select className="select">
                  <option>Tidak ada preferensi</option>
                  <option>Indoor</option>
                  <option>Outdoor (Garden)</option>
                </select>
              </div>
              <div className="field" style={{gridColumn:'1 / -1'}}>
                <label>Catatan Khusus</label>
                <textarea className="input" rows={2} placeholder="Anniversary, alergi, request khusus…" />
              </div>
            </div>
            <div className="row gap-2 mt-3" style={{justifyContent:'flex-end'}}>
              <Btn onClick={() => setShowForm(false)}>Batal</Btn>
              <Btn tone="primary" icon="check" onClick={() => { setShowForm(false); pushToast({msg:'Reservasi berhasil dibuat & WA dikirim', type:'success'}); }}>Simpan & Kirim Konfirmasi</Btn>
            </div>
          </div>
        </Card>
      )}

      <Card>
        <div className="card-header">
          <h3 className="card-title">Jadwal Reservasi — {view === 'today' ? formatDateID(TODAY) : 'Minggu Ini'}</h3>
          <p className="card-desc">Klik baris untuk lihat detail / ubah</p>
        </div>
        <div className="card-body flush">
          <div className="table-wrap">
            <table className="table">
              <thead>
                <tr>
                  <th>Waktu</th>
                  <th>Tamu</th>
                  <th>Kontak</th>
                  <th className="num">Pax</th>
                  <th>Meja</th>
                  <th>Status</th>
                  <th>Catatan</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {enriched.sort((a,b)=>a.time.localeCompare(b.time)).map(r => {
                  const tone = r.status === 'arrived' ? 'success'
                    : r.status === 'soon' ? 'warn'
                    : r.status === 'no-show' ? 'danger'
                    : 'accent';
                  const label = r.status === 'arrived' ? 'Sudah Datang'
                    : r.status === 'soon' ? `Sebentar lagi (${r.diff} min)`
                    : r.status === 'no-show' ? 'No-show'
                    : `Upcoming (${Math.floor(r.diff/60)}j ${r.diff%60}m)`;
                  return (
                    <tr key={r.id}>
                      <td className="mono" style={{fontWeight:600, fontSize:15}}>{r.time}</td>
                      <td>
                        <div style={{fontWeight:500}}>{r.name}</div>
                        <div className="muted text-sm mono">{r.id}</div>
                      </td>
                      <td className="mono text-sm">{r.phone}</td>
                      <td className="num mono" style={{fontWeight:600}}>{r.guests}</td>
                      <td><span className="badge accent">{r.table}</span></td>
                      <td><Pill tone={tone}>{label}</Pill></td>
                      <td className="muted text-sm" style={{maxWidth:280}}>{r.note}</td>
                      <td>
                        <div className="row gap-1">
                          {r.status === 'soon' || r.status === 'upcoming' ? (
                            <button className="btn primary sm" onClick={() => pushToast({msg:`${r.name} di-check-in`, type:'success'})}><Icon name="check" size={12}/> Check-in</button>
                          ) : null}
                          <button className="btn ghost sm"><Icon name="more" size={13}/></button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </Card>

      <div className="grid-2 mt-4">
        <Card>
          <div className="card-header">
            <h3 className="card-title">Tips Operasi</h3>
          </div>
          <div className="card-body">
            <ul style={{margin:0, paddingLeft:18, lineHeight:1.7, fontSize:14}}>
              <li>Tamu otomatis di-WA <b>1 jam sebelum</b> waktu reservasi.</li>
              <li>Status <b>no-show</b> aktif setelah <b>30 menit</b> dari jadwal tanpa check-in.</li>
              <li>Meja yang reserved otomatis terblokir dari order baru <b>15 menit sebelum</b>.</li>
              <li>Walk-in tetap dilayani jika ada meja tersedia & tidak konflik dengan reservasi.</li>
            </ul>
          </div>
        </Card>
        <Card>
          <div className="card-header">
            <h3 className="card-title">Channel Reservasi</h3>
            <p className="card-desc">Sumber booking 30 hari terakhir</p>
          </div>
          <div className="card-body">
            <div style={{display:'flex', flexDirection:'column', gap:10}}>
              {[
                { label: 'WhatsApp Bisnis', count: 142, pct: 56, color: 'hsl(142 60% 45%)' },
                { label: 'Walk-in Phone',   count: 68,  pct: 27, color: 'hsl(var(--accent))' },
                { label: 'Google Maps',     count: 28,  pct: 11, color: 'hsl(215 70% 55%)' },
                { label: 'Instagram DM',    count: 16,  pct: 6,  color: 'hsl(330 70% 55%)' },
              ].map(c => (
                <div key={c.label}>
                  <div className="row between" style={{fontSize:13, marginBottom:4}}>
                    <span style={{fontWeight:500}}>{c.label}</span>
                    <span className="mono">{c.count} ({c.pct}%)</span>
                  </div>
                  <div className="bar-h"><div style={{width: c.pct + '%', background: c.color}} /></div>
                </div>
              ))}
            </div>
          </div>
        </Card>
      </div>
    </>
  );
}

window.ReservasiPage = ReservasiPage;
