// Manual New Rx entry — blank-start path (V5). Scripted: verbal order for Curtis Dunbar.

function ManualEntryForm({ onClose, onSent, nav, showToast }) {
  const { useState } = React;
  const [phase, setPhase] = useState('form'); // form | processing | paid
  const [source, setSource] = useState('verbal'); // verbal | hardcopy | transfer
  const [takenBy, setTakenBy] = useState('C. Schaffner, PharmD');
  const [query, setQuery] = useState('');
  const [patient, setPatient] = useState(null);
  const [open, setOpen] = useState(false);
  const [drug, setDrug] = useState('');
  const [prescriber, setPrescriber] = useState('');
  const [sigInput, setSigInput] = useState('');
  const [payer, setPayer] = useState('cash');

  const normSig = sigInput.trim().replace(/\s+/g, ' ').toUpperCase();
  const sigText = SIG_CODES[normSig] || null;

  const matches = query.trim().length >= 2 && !patient
    ? PATIENT_DIR.filter(p => p.name.toLowerCase().indexOf(query.trim().toLowerCase()) !== -1).slice(0, 5)
    : [];

  const pickPatient = (p) => {
    setPatient(p);
    setQuery(p.name);
    setOpen(false);
    setPayer(p.plan.id);
  };

  const clearPatient = () => { setPatient(null); setPayer('cash'); };

  const a = MANUAL_RX.adj;
  const gp = a.copay + a.reimb - a.acq;
  const total = a.copay + a.reimb;
  const margin = (gp / total * 100).toFixed(1) + '%';
  const money = (n) => '$' + n.toFixed(2);

  const submit = () => {
    if (phase !== 'form') return;
    if (!patient) return showToast('Select a patient first.');
    if (!(source === 'verbal' && patient.name === 'Curtis Dunbar')) {
      return showToast('Demo supports the scripted path — verbal order for Curtis Dunbar.');
    }
    if (normSig !== '1C TID X10D') {
      return showToast('Enter the verbal sig as a code (e.g. 1C TID x10D) so it expands.');
    }
    setPhase('processing');
    window.setTimeout(() => setPhase('paid'), 1000);
  };

  return (
    <div>
      <div className="scrim" onClick={phase === 'processing' ? undefined : onClose}></div>
      <div className="station" style={{ width: 'min(880px, 94vw)' }}>
        <div className="station-head">
          <span className="kicker">Manual Rx entry · new prescription</span>
          <span className="badge neutral">Blank start</span>
          <button className="xclose" onClick={onClose}>✕</button>
        </div>
        <div style={{ overflowY: 'auto' }}>

          {/* Source */}
          <div className="entry-sec">
            <div className="field-row">
              <span className="flab">Source</span>
              <div className="seg">
                {[['verbal', 'Verbal order'], ['hardcopy', 'Hard copy'], ['transfer', 'Transfer']].map(s => (
                  <button key={s[0]} className={source === s[0] ? 'on' : ''} onClick={() => setSource(s[0])}>{s[1]}</button>
                ))}
              </div>
            </div>
            {source === 'verbal' ? (
              <div className="field-row">
                <span className="flab">Taken by</span>
                <div>
                  <select className="inp" style={{ width: 240 }} value={takenBy} onChange={e => setTakenBy(e.target.value)}>
                    <option>C. Schaffner, PharmD</option>
                    <option>J. Okada, PharmD</option>
                  </select>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6 }}>Verbal orders must be received and entered by a pharmacist.</div>
                </div>
              </div>
            ) : null}
          </div>

          {/* Patient search */}
          <div className="entry-sec">
            <div className="field-row">
              <span className="flab">Patient</span>
              <div className="ta-wrap">
                <input className="inp" placeholder="Search patients by name…" value={query}
                  onChange={e => { setQuery(e.target.value); setOpen(true); if (patient) clearPatient(); }}
                  onFocus={() => setOpen(true)}></input>
                {open && matches.length ? (
                  <div className="ta-drop">
                    {matches.map(p => (
                      <div className="ta-opt" key={p.name} onClick={() => pickPatient(p)}>
                        <span style={{ fontWeight: 600 }}>{p.name}</span>
                        <span style={{ color: 'var(--ink-3)', fontSize: 12, marginLeft: 8 }}>DOB {p.dob} · {p.store}</span>
                      </div>
                    ))}
                  </div>
                ) : null}
              </div>
            </div>
            {patient ? (
              <div className="match" style={{ marginTop: 4 }}>
                <span className="check">✓ Selected</span>
                <span style={{ fontWeight: 700 }}>{patient.name}</span>
                <span style={{ color: 'var(--ink-2)' }}>DOB {patient.dob} · {patient.store}</span>
                <button className="pt-link" style={{ fontSize: 13, marginLeft: 'auto' }} onClick={() => nav.goPatient(routePatient(patient.name))}>View profile →</button>
              </div>
            ) : null}
          </div>

          {/* Prescriber + drug + sig */}
          <div className="entry-sec">
            <div className="field-row">
              <span className="flab">Prescriber</span>
              <input className="inp" placeholder="Prescriber name, clinic" value={prescriber} onChange={e => setPrescriber(e.target.value)}></input>
            </div>
            <div className="field-row">
              <span className="flab">Drug</span>
              <input className="inp" placeholder="Drug, strength, form" value={drug} onChange={e => setDrug(e.target.value)}></input>
            </div>
            <div className="field-row">
              <span className="flab">Sig</span>
              <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
                <input className="inp" style={{ width: 200 }} placeholder="Sig code (e.g. 1C TID x10D)" value={sigInput} onChange={e => setSigInput(e.target.value)}></input>
                <span style={{ color: 'var(--ink-3)' }}>→</span>
                {sigText ? (
                  <span className="sig-line" style={{ fontSize: 15 }}>“{sigText}”</span>
                ) : (
                  <span style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>Sig code will expand on match.</span>
                )}
              </div>
            </div>
            <div className="field-row">
              <span className="flab">Dispense</span>
              <div style={{ display: 'flex', gap: 10 }}>
                <input className="inp" style={{ width: 90 }} placeholder="Qty" aria-label="Quantity"></input>
                <input className="inp" style={{ width: 110 }} placeholder="Days supply" aria-label="Days supply"></input>
                <input className="inp" style={{ width: 100 }} placeholder="Refills" aria-label="Refills"></input>
              </div>
            </div>
          </div>

          {/* Billing */}
          <div className="entry-sec">
            <div className="field-row">
              <span className="flab">Billing</span>
              {patient && patient.plan.id !== 'cash' ? (
                <div className="ins-radio">
                  <button className={'ins-card' + (payer === patient.plan.id ? ' on' : '')} onClick={() => setPayer(patient.plan.id)}>
                    <div className="plan">{payer === patient.plan.id ? '● ' : '○ '}{patient.plan.name}</div>
                    <div className="det">{patient.plan.det}</div>
                  </button>
                  <button className={'ins-card' + (payer === 'cash' ? ' on' : '')} onClick={() => setPayer('cash')}>
                    <div className="plan">{payer === 'cash' ? '● ' : '○ '}Cash</div>
                    <div className="det">Usual &amp; customary</div>
                  </button>
                </div>
              ) : (
                <span style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>{patient ? 'Cash — no plan on file.' : 'Select a patient to load plan on file.'}</span>
              )}
            </div>
          </div>

          {/* Submit / result */}
          <div className="entry-sec" style={{ borderBottom: 'none' }}>
            {phase === 'paid' ? (
              <div className="paid-panel">
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
                  <span className="chip-status paid">PAID</span>
                  <span style={{ fontSize: 13, color: 'var(--ink-2)' }}>SilverScript (Part D) · response in 0.8 s</span>
                </div>
                <div className="rows">
                  <div><div className="v">{money(a.copay)}</div><div className="k">Copay</div></div>
                  <div><div className="v">{money(a.reimb)}</div><div className="k">Plan paid</div></div>
                  <div><div className="v">{money(total)}</div><div className="k">Total</div></div>
                  <div><div className="v">{money(a.acq)}</div><div className="k">Acquisition</div></div>
                  <div><div className="v" style={{ color: 'var(--moss)' }}>{money(gp)}</div><div className="k">Gross profit · {margin}</div></div>
                </div>
                <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 14 }}>
                  <button className="btn-primary" style={{ flex: '0 0 auto', padding: '11px 26px' }}
                    onClick={() => onSent(MANUAL_RX, 'BUR-2046135 created · Data Entry, Burlington')}>
                    Send to Fill Queue
                  </button>
                </div>
              </div>
            ) : (
              <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 14 }}>
                {phase === 'processing' ? (
                  <span style={{ fontSize: 13, color: 'var(--ink-2)' }}>Adjudicating with SilverScript…</span>
                ) : null}
                <button className="btn-primary" style={{ flex: '0 0 auto', padding: '11px 26px', opacity: phase === 'processing' ? 0.6 : 1 }}
                  onClick={submit} disabled={phase === 'processing'}>
                  {phase === 'processing' ? 'Submitting…' : 'Submit Claim'}
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ManualEntryForm });
