/* global React, Icon, MOCK, fmtRp */
const { useState: useStateInb } = React;

const STATUS_INB = {
  ok:        { label: "Cocok",          chip: "chip-green" },
  diff:      { label: "Ada selisih",    chip: "chip-amber" },
  scheduled: { label: "Dijadwalkan",    chip: "chip-blue"  },
  receiving: { label: "Sedang diterima",chip: "chip-brand" },
};

function InboundPage() {
  const [tab, setTab] = useStateInb('all');
  const [openId, setOpen] = useStateInb(null);
  const [newOpen, setNewOpen] = useStateInb(false);
  const [from, setFrom] = useStateInb('');
  const [to, setTo] = useStateInb('');

  const INBOUNDS = MOCK.INBOUND || [];
  const dateFiltered = INBOUNDS.filter(x =>
    window.inRange(x._raw?.scheduledAt || x._raw?.receivedAt || x._raw?.createdAt, from, to)
  );

  const list = dateFiltered.filter(x => {
    if (tab === 'diff') return x.status === 'diff';
    if (tab === 'scheduled') return x.status === 'scheduled';
    if (tab === 'done') return x.status === 'ok';
    return true;
  });

  const open = INBOUNDS.find(x => x.id === openId);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Penerimaan Barang</h1>
          <p className="page-sub">Tiap stok masuk ke gudang dihitung, difoto, &amp; dicocokkan ke surat jalan — agar stok di sistem selalu sinkron dengan stok fisik</p>
        </div>
        <div className="page-actions">
          <button className="btn btn-secondary"><Icon.download/> Ekspor</button>
          <button className="btn btn-primary" onClick={() => setNewOpen(true)}>
            <Icon.plus/> Jadwalkan Kiriman
          </button>
        </div>
      </div>

      {/* Stat strip */}
      <div className="grid-4" style={{ marginBottom: 18 }}>
        <Stat label="Diterima bulan ini" value="6 kiriman"/>
        <Stat label="Total unit masuk" value="2.142"/>
        <Stat label="Selisih (open)" value="1" tone="amber"/>
        <Stat label="Akurasi terima" value="99.4%" tone="green"/>
      </div>

      <div style={{ marginBottom:14, display:'flex', justifyContent:'flex-end' }}>
        <window.DateRangeFilter
          from={from} to={to}
          onChange={({ from, to }) => { setFrom(from); setTo(to); }}
        />
      </div>

      <div className="tabs">
        <button className={`tab ${tab==='all'?'active':''}`} onClick={()=>setTab('all')}>
          Semua<span className="count">{dateFiltered.length}</span>
        </button>
        <button className={`tab ${tab==='scheduled'?'active':''}`} onClick={()=>setTab('scheduled')}>
          Dijadwalkan<span className="count">{dateFiltered.filter(x=>x.status==='scheduled').length}</span>
        </button>
        <button className={`tab ${tab==='diff'?'active':''}`} onClick={()=>setTab('diff')}>
          Ada selisih<span className="count">{dateFiltered.filter(x=>x.status==='diff').length}</span>
        </button>
        <button className={`tab ${tab==='done'?'active':''}`} onClick={()=>setTab('done')}>
          Cocok<span className="count">{dateFiltered.filter(x=>x.status==='ok').length}</span>
        </button>
      </div>

      <div className="card" style={{ overflow: 'hidden' }}>
        <table className="table">
          <thead>
            <tr>
              <th>ID</th>
              <th>Gudang</th>
              <th>Tanggal</th>
              <th>Surat Jalan</th>
              <th style={{ textAlign:'right' }}>Expected</th>
              <th style={{ textAlign:'right' }}>Diterima</th>
              <th>Status</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {list.map(inb => {
              const meta = STATUS_INB[inb.status];
              const diff = inb.received - inb.expected;
              return (
                <tr key={inb.id} onClick={()=>setOpen(inb.id)} style={{ cursor:'pointer' }}>
                  <td><span className="mono">{inb.id}</span></td>
                  <td>
                    <span style={{ display:'inline-flex', alignItems:'center', gap:6 }}>
                      <Icon.box/> {inb.warehouse}
                    </span>
                  </td>
                  <td style={{ color:'var(--ink-500)' }}>{inb.date}</td>
                  <td><span className="mono" style={{ fontSize:12 }}>{inb.suratJalan}</span></td>
                  <td style={{ textAlign:'right', fontWeight:600 }}>{inb.expected}</td>
                  <td style={{ textAlign:'right', fontWeight:700, color: diff < 0 ? 'var(--amber)' : (inb.status==='scheduled' ? 'var(--ink-400)' : 'var(--green)') }}>
                    {inb.status==='scheduled' ? '—' : inb.received}
                    {diff < 0 && <span style={{ fontSize:11, marginLeft:6, color:'var(--amber)' }}>({diff})</span>}
                  </td>
                  <td><span className={`chip ${meta.chip}`}><span className="chip-dot"/>{meta.label}</span></td>
                  <td style={{ textAlign:'right' }}>
                    <button className="btn btn-secondary btn-sm" onClick={(e)=>{ e.stopPropagation(); setOpen(inb.id); }}>Detail</button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {open && <InboundDetail inb={open} onClose={()=>setOpen(null)}/>}
      {newOpen && <NewInboundModal onClose={()=>setNewOpen(false)}/>}
    </div>
  );
}

function InboundDetail({ inb, onClose }) {
  const meta = STATUS_INB[inb.status];
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{ maxWidth: 720 }} onClick={e=>e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--ink-500)' }}>
              Penerimaan {inb.id}
            </div>
            <h2 style={{ margin:'4px 0 0', fontSize:20, fontWeight:800 }}>
              Gudang {inb.warehouse} · {inb.date}
            </h2>
          </div>
          <button className="tb-icon-btn" onClick={onClose}><Icon.x/></button>
        </div>

        <div style={{ padding:'18px 22px', display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:14, borderBottom:'1px solid var(--border)' }}>
          <div>
            <div style={{ fontSize:11, color:'var(--ink-500)', fontWeight:600, textTransform:'uppercase', letterSpacing:'0.05em' }}>Surat Jalan</div>
            <div className="mono" style={{ fontSize:13, fontWeight:700, marginTop:4 }}>{inb.suratJalan}</div>
          </div>
          <div>
            <div style={{ fontSize:11, color:'var(--ink-500)', fontWeight:600, textTransform:'uppercase', letterSpacing:'0.05em' }}>Kurir</div>
            <div style={{ fontSize:13, fontWeight:600, marginTop:4 }}>{inb.courier}</div>
          </div>
          <div>
            <div style={{ fontSize:11, color:'var(--ink-500)', fontWeight:600, textTransform:'uppercase', letterSpacing:'0.05em' }}>Status</div>
            <div style={{ marginTop:4 }}>
              <span className={`chip ${meta.chip}`}><span className="chip-dot"/>{meta.label}</span>
            </div>
          </div>
        </div>

        <ReceiveSection inb={inb} onDone={onClose}/>
      </div>
    </div>
  );
}

function ReceiveSection({ inb, onDone }) {
  // Edit mode is allowed when status is 'scheduled' (about to receive) or
  // 'diff' (re-record after correction). 'matched' / 'ok' = readonly.
  const editable = inb.status === 'scheduled' || inb.status === 'diff';
  const items = inb._raw?.items || inb.items || [];
  const [counts, setCounts] = useStateInb(() => {
    const map = {};
    for (const it of items) {
      map[it.id || it.sku] = {
        received: it.received ?? it.expected,
        diffNote: it.diffNote ?? it.note ?? '',
      };
    }
    return map;
  });
  const [photos, setPhotos] = useStateInb(inb._raw?.photos || []);
  const [busy, setBusy] = useStateInb(false);
  const [error, setError] = useStateInb('');

  const update = (key, patch) => setCounts({ ...counts, [key]: { ...counts[key], ...patch } });

  const upload = async (file) => {
    if (!file) return;
    setBusy(true);
    try {
      const fd = new FormData();
      fd.append('file', file);
      const r = await fetch('/api/uploads', { method: 'POST', body: fd, credentials: 'include' });
      if (!r.ok) throw new Error('upload gagal');
      const data = await r.json();
      setPhotos([...photos, data.url]);
    } catch (e) {
      alert('Gagal upload: ' + e.message);
    } finally { setBusy(false); }
  };

  const submit = async () => {
    if (!inb._raw?.id) return;
    setError('');
    setBusy(true);
    try {
      const itemsPayload = items
        .filter(it => it.id) // need item id from API
        .map(it => ({
          itemId: it.id,
          received: Number(counts[it.id]?.received ?? 0),
          diffNote: counts[it.id]?.diffNote || undefined,
        }));
      await window.Api.post(`/api/inbound/${encodeURIComponent(inb._raw.id)}/receive`, {
        items: itemsPayload,
        photos: photos.length > 0 ? photos : undefined,
      });
      await window.Api.loadAppData();
      onDone();
      window.location.reload();
    } catch (err) {
      setError(err.body?.message || err.message || 'Gagal');
      setBusy(false);
    }
  };

  return (
    <>
      <div style={{ padding:'18px 22px' }}>
        <div style={{ fontSize:13, fontWeight:700, marginBottom:10 }}>Item ({items.length} SKU)</div>
        <div className="card" style={{ overflow:'hidden' }}>
          <table className="table">
            <thead>
              <tr>
                <th>SKU</th>
                <th>Produk</th>
                <th style={{ textAlign:'right' }}>Expected</th>
                <th style={{ textAlign:'right' }}>Diterima</th>
                <th style={{ textAlign:'right' }}>Selisih</th>
                <th>Catatan</th>
              </tr>
            </thead>
            <tbody>
              {items.map(it => {
                const key = it.id || it.sku;
                const received = counts[key]?.received ?? it.received ?? it.expected;
                const d = Number(received) - it.expected;
                return (
                  <tr key={key}>
                    <td><span className="mono">{it.sku}</span></td>
                    <td>{it.name}</td>
                    <td style={{ textAlign:'right' }}>{it.expected}</td>
                    <td style={{ textAlign:'right' }}>
                      {editable ? (
                        <input
                          type="number"
                          min="0"
                          className="input"
                          style={{ width:80, textAlign:'right' }}
                          value={counts[key]?.received ?? ''}
                          onChange={e => update(key, { received: e.target.value })}
                          placeholder={String(it.expected)}
                        />
                      ) : (
                        <strong>{it.received}</strong>
                      )}
                    </td>
                    <td style={{ textAlign:'right', fontWeight:700, color: d < 0 ? 'var(--amber)' : (d > 0 ? 'var(--blue)' : 'var(--ink-400)') }}>
                      {received === '' || received == null ? '—' : (d === 0 ? '0' : (d > 0 ? `+${d}` : d))}
                    </td>
                    <td>
                      {editable ? (
                        <input
                          className="input"
                          style={{ fontSize:12 }}
                          value={counts[key]?.diffNote || ''}
                          onChange={e => update(key, { diffNote: e.target.value })}
                          placeholder="Catatan…"
                        />
                      ) : (
                        <span style={{ fontSize:12, color:'var(--ink-500)' }}>{it.diffNote || it.note || ''}</span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {/* Photo upload */}
        <div style={{ marginTop:14 }}>
          <div style={{ fontSize:11, color:'var(--ink-500)', fontWeight:600, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:8 }}>Foto Bukti ({photos.length})</div>
          <div style={{ display:'flex', flexWrap:'wrap', gap:8, alignItems:'center' }}>
            {photos.map((url, idx) => (
              <a key={idx} href={url} target="_blank" rel="noopener" style={{ display:'inline-block' }}>
                <img src={url} alt="bukti" style={{ width:72, height:72, objectFit:'cover', borderRadius:8, border:'1px solid var(--border)' }}/>
              </a>
            ))}
            {editable && (
              <label className="btn btn-secondary btn-sm" style={{ cursor:'pointer' }}>
                <Icon.plus/> Tambah Foto
                <input type="file" accept="image/*" style={{ display:'none' }} onChange={e => upload(e.target.files?.[0])}/>
              </label>
            )}
          </div>
        </div>

        {error && <div style={{ marginTop:12, padding:'8px 12px', background:'#fee2e2', color:'#991b1b', borderRadius:8, fontSize:12 }}>{error}</div>}
      </div>

      <div className="modal-foot">
        <button className="btn btn-secondary" onClick={onDone} disabled={busy}>Tutup</button>
        {editable && (
          <button className="btn btn-primary" onClick={submit} disabled={busy}>
            {busy ? 'Menyimpan…' : 'Simpan & Tandai Diterima'}
          </button>
        )}
      </div>
    </>
  );
}

function NewInboundModal({ onClose }) {
  const WAREHOUSES = [
    { id:'wh_sub', label:'Surabaya' },
    { id:'wh_dpk', label:'Depok' },
    { id:'wh_med', label:'Medan' },
  ];
  const [warehouseId, setWh] = useStateInb('wh_sub');
  const [scheduledAt, setScheduledAt] = useStateInb(new Date().toISOString().slice(0, 10));
  const [suratJalan, setSuratJalan] = useStateInb('');
  const [courier, setCourier] = useStateInb('');
  const [notes, setNotes] = useStateInb('');
  const [items, setItems] = useStateInb([]);
  const [busy, setBusy] = useStateInb(false);
  const [error, setError] = useStateInb('');

  const products = window.MOCK?.PRODUCTS || [];
  const warehouseLabel = WAREHOUSES.find(w => w.id === warehouseId)?.label || warehouseId;

  const addItem = () => {
    const first = products[0];
    if (!first) return;
    setItems([...items, {
      productId: first.productId || first.sku,
      sku: first.sku,
      name: first.name,
      expected: 1,
    }]);
  };
  const updateItem = (idx, patch) => setItems(items.map((it, i) => i === idx ? { ...it, ...patch } : it));
  const removeItem = (idx) => setItems(items.filter((_, i) => i !== idx));

  const submit = async () => {
    setError('');
    if (items.length === 0) { setError('Tambahkan minimal 1 item'); return; }
    if (!suratJalan.trim()) { setError('No. Surat Jalan wajib diisi'); return; }
    setBusy(true);
    try {
      await window.Api.post('/api/inbound', {
        warehouseId,
        scheduledAt,
        suratJalan,
        courier: courier || undefined,
        notes: notes || undefined,
        items: items.map(it => ({
          productId: it.productId,
          sku: it.sku,
          name: it.name,
          expected: Number(it.expected) || 0,
        })),
      });
      await window.Api.loadAppData();
      onClose();
      window.location.reload();
    } catch (err) {
      setError(err.body?.message || err.message || 'Gagal');
      setBusy(false);
    }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{ maxWidth: 720 }} onClick={e=>e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--ink-500)' }}>
              Penerimaan baru
            </div>
            <h2 style={{ margin:'4px 0 0', fontSize:20, fontWeight:800 }}>Jadwalkan Kiriman ke Gudang</h2>
          </div>
          <button className="tb-icon-btn" onClick={onClose}><Icon.x/></button>
        </div>
        <div style={{ padding:'20px 22px', display:'flex', flexDirection:'column', gap:14 }}>
          {error && <div style={{ padding:'10px 14px', background:'#fee2e2', color:'#991b1b', borderRadius:8, fontSize:13 }}>{error}</div>}

          <Field label="Pilih gudang tujuan">
            <div style={{ display:'flex', gap:8 }}>
              {WAREHOUSES.map(w => (
                <button key={w.id} type="button" className={`pick ${warehouseId===w.id?'on':''}`} onClick={()=>setWh(w.id)}>
                  <Icon.box/> {w.label}
                </button>
              ))}
            </div>
          </Field>

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:12 }}>
            <Field label="Tanggal estimasi tiba">
              <input className="input" type="date" value={scheduledAt} onChange={e=>setScheduledAt(e.target.value)}/>
            </Field>
            <Field label="No. Surat Jalan / Resi">
              <input className="input" value={suratJalan} onChange={e=>setSuratJalan(e.target.value)} placeholder="SJ-BJ-2026-105"/>
            </Field>
            <Field label="Kurir / pengirim">
              <input className="input" value={courier} onChange={e=>setCourier(e.target.value)} placeholder="JNE Trucking, Lion Parcel"/>
            </Field>
          </div>

          <div>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:8 }}>
              <strong style={{ fontSize:13 }}>Item yang dikirim ({items.length})</strong>
              <button type="button" className="btn btn-secondary btn-sm" onClick={addItem}><Icon.plus/> Tambah Item</button>
            </div>
            {items.length === 0 ? (
              <div style={{ padding:18, textAlign:'center', color:'var(--ink-500)', background:'var(--surface-2)', borderRadius:10, fontSize:13 }}>
                Belum ada item. Klik <strong>Tambah Item</strong> untuk pilih SKU + qty yang dikirim.
              </div>
            ) : (
              <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                {items.map((it, idx) => (
                  <div key={idx} style={{ display:'grid', gridTemplateColumns:'2.5fr 100px 32px', gap:6, alignItems:'center' }}>
                    <select
                      className="input"
                      value={it.productId}
                      onChange={(e) => {
                        const p = products.find(x => (x.productId || x.sku) === e.target.value);
                        if (p) updateItem(idx, { productId: p.productId || p.sku, sku: p.sku, name: p.name });
                      }}
                    >
                      {products.map(p => <option key={p.productId || p.sku} value={p.productId || p.sku}>{p.sku} — {p.name}</option>)}
                    </select>
                    <input className="input" type="number" min="1" value={it.expected} onChange={e=>updateItem(idx, { expected: e.target.value })} placeholder="Qty"/>
                    <button type="button" className="tb-icon-btn" onClick={() => removeItem(idx)}><Icon.x/></button>
                  </div>
                ))}
              </div>
            )}
          </div>

          <Field label="Catatan untuk tim gudang">
            <textarea className="input" rows="2" value={notes} onChange={e=>setNotes(e.target.value)} placeholder="Mis. Mohon cek kondisi mug, sebelumnya pernah ada yang pecah."/>
          </Field>

          <div style={{ fontSize:12.5, color:'var(--ink-500)', padding:'10px 12px', background:'var(--surface-2)', borderRadius:8 }}>
            💡 Tim gudang <strong>{warehouseLabel}</strong> akan menghitung tiap SKU saat barang tiba, foto kondisi, dan mencocokkan ke surat jalan ini. Stok masuk sistem otomatis &amp; sinkron ke semua marketplace.
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn btn-secondary" onClick={onClose} disabled={busy}>Batal</button>
          <button className="btn btn-primary" onClick={submit} disabled={busy || items.length === 0}>{busy ? 'Menyimpan…' : 'Jadwalkan'}</button>
        </div>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return (
    <label style={{ display:'flex', flexDirection:'column', gap:6 }}>
      <span style={{ fontSize:12, fontWeight:600, color:'var(--ink-700)' }}>{label}</span>
      {children}
    </label>
  );
}

function Stat({ label, value, tone }) {
  const color = tone === 'amber' ? 'var(--amber)' : tone === 'rose' ? 'var(--rose)' : tone === 'green' ? 'var(--green)' : 'var(--ink-900)';
  return (
    <div className="card" style={{ padding:'16px 18px' }}>
      <div style={{ fontSize:12, fontWeight:600, color:'var(--ink-500)' }}>{label}</div>
      <div style={{ fontSize:24, fontWeight:800, letterSpacing:'-0.02em', marginTop:4, color }}>{value}</div>
    </div>
  );
}

window.InboundPage = InboundPage;
