// TreatmentPlan.jsx — HITL treatment plan draft; wired to Voice Scribe SOAP + perio chart.
const { useState, useEffect, useMemo, useCallback } = React;

const AB3030 =
  'AI-assisted treatment planning draft — information only, not diagnosis or chart submission. ' +
  'Confirm with a licensed dentist. California AB 3030 disclosure applies.';

function HitlBanner() {
  return (
    <div className="banner warn" style={{ marginBottom: 14 }}>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--seal)" strokeWidth="1.8">
        <path d="M12 4l8.5 15H3.5z" /><path d="M12 10v4.5M12 17.4v.1" />
      </svg>
      <div>
        <b>Draft for clinician review — not submitted to chart.</b> Status: <b>PENDING_HITL_REVIEW</b>.
      </div>
    </div>
  );
}

function TreatmentPlan() {
  const SS = () => window.SuiteState;
  const BR = () => window.SuiteBridge;

  const [plan, setPlan] = useState(null);
  const [msg, setMsg] = useState('');
  const [copied, setCopied] = useState(false);

  const loadPlan = useCallback(() => {
    const s = SS();
    if (!s) return;
    setPlan(s.getTreatmentPlan());
  }, []);

  useEffect(() => { loadPlan(); }, [loadPlan]);

  const scribe = useMemo(() => {
    const s = SS();
    return s ? s.getScribeNote() : null;
  }, [plan]);

  const importFromScribe = useCallback(() => {
    const s = SS();
    const b = BR();
    if (!s || !b) return;
    const note = s.getScribeNote();
    if (!note || !note.note) {
      setMsg('No SOAP draft found — generate one in Voice Scribe first.');
      return;
    }
    const draft = b.planFromSOAP(note.note, {
      scribeRef: note.id,
      title: 'Plan from scribe · ' + (note.updatedAt || '').slice(0, 10),
    });
    const saved = s.saveTreatmentPlan(draft);
    setPlan(saved);
    setMsg('Imported procedures from SOAP Assessment/Plan.');
  }, []);

  const importFromPerio = useCallback(() => {
    const s = SS();
    const b = BR();
    if (!s || !b) return;
    const chart = s.getPerioChart();
    if (!chart) {
      setMsg('No perio chart data — chart findings in Periodontal Charting first.');
      return;
    }
    const procs = b.proceduresFromPerio(chart);
    const base = plan || b.planFromSOAP({ assessment: '', plan: '' }, { title: 'Perio-driven plan draft' });
    const merged = b.mergePerioIntoPlan(base, procs);
    merged.perioRef = chart.id;
    const saved = s.saveTreatmentPlan(merged);
    setPlan(saved);
    setMsg('Added perio-recommended procedures (SRP / maintenance drafts).');
  }, [plan]);

  const toggleProc = (phaseId, procId) => {
    setPlan((prev) => {
      if (!prev) return prev;
      const next = JSON.parse(JSON.stringify(prev));
      next.phases.forEach((ph) => {
        if (ph.id !== phaseId) return;
        ph.procedures.forEach((p) => {
          if (p.id === procId) p.status = p.status === 'approved' ? 'draft' : 'approved';
        });
      });
      const s = SS();
      if (s) s.saveTreatmentPlan(next);
      return next;
    });
  };

  const exportSummary = async () => {
    if (!plan) return;
    const lines = [
      'TREATMENT PLAN — DRAFT (NOT SUBMITTED TO CHART)',
      'Status: PENDING_HITL_REVIEW',
      plan.title || '',
      '',
    ];
    (plan.phases || []).forEach((ph) => {
      lines.push('## ' + ph.name);
      (ph.procedures || []).forEach((p) => {
        lines.push('- [' + (p.status || 'draft') + '] ' + p.label + (p.tooth ? ' (# ' + p.tooth + ')' : ''));
      });
      lines.push('');
    });
    if (plan.scribeRef) lines.push('Linked scribe: ' + plan.scribeRef);
    if (plan.perioRef) lines.push('Linked perio chart: ' + plan.perioRef);
    lines.push('', '—', AB3030);
    try {
      await navigator.clipboard.writeText(lines.join('\n'));
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      setMsg('Copy failed — select text manually.');
    }
  };

  const goScribe = () => { location.hash = '#scribe'; };
  const goPerio = () => { location.hash = '#perio-chart'; };

  return (
    <div className="wrap">
      <div className="banner info" style={{ marginBottom: 14 }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--blue)" strokeWidth="1.8">
          <path d="M12 4l8.5 15H3.5z" /><path d="M12 10v4.5M12 17.4v.1" />
        </svg>
        <div>{AB3030}</div>
      </div>
      <HitlBanner />

      <div className="card">
        <h3>Treatment plan draft</h3>
        <div className="hint">
          Phases and procedures pre-filled from Voice Scribe SOAP or periodontal findings. Approve items after clinical review.
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 12 }}>
          <button type="button" className="btn btn-primary btn-sm" onClick={importFromScribe}>
            Import from SOAP scribe
          </button>
          <button type="button" className="btn btn-sm" onClick={importFromPerio}>
            Add from perio chart
          </button>
          {plan && (
            <button type="button" className="btn btn-sm" onClick={exportSummary}>
              {copied ? 'Copied' : 'Copy plan summary'}
            </button>
          )}
          {scribe && (
            <button type="button" className="btn btn-sm btn-ghost" onClick={goScribe}>
              Open scribe {scribe.updatedAt ? '· ' + new Date(scribe.updatedAt).toLocaleString() : ''}
            </button>
          )}
          <button type="button" className="btn btn-sm btn-ghost" onClick={goPerio}>
            Open perio chart
          </button>
        </div>
        {msg && <div className="banner ok" style={{ marginTop: 12, fontSize: 12 }}>{msg}</div>}
      </div>

      {!plan || !(plan.phases && plan.phases.length) ? (
        <div className="card" style={{ marginTop: 16 }}>
          <div className="hint">No plan yet. Generate a SOAP draft in Voice Scribe, then use <b>Import from SOAP scribe</b>, or chart perio findings first.</div>
        </div>
      ) : (
        <div style={{ marginTop: 16 }}>
          <div className="sectiontitle">{plan.title || 'Phases'}</div>
          {plan.phases.map((ph) => (
            <div className="card" key={ph.id} style={{ marginBottom: 12 }}>
              <h3>
                Phase {ph.sequence}: {ph.name}
                <span className="chip tone" style={{ marginLeft: 8 }}>{(ph.procedures || []).length} items</span>
              </h3>
              {(ph.procedures || []).map((p) => (
                <div className="list-row" key={p.id}>
                  <div
                    className={'cbox' + (p.status === 'approved' ? ' done' : '')}
                    onClick={() => toggleProc(ph.id, p.id)}
                    title="Toggle clinician-approved (demo)"
                  >
                    {p.status === 'approved' && (
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2">
                        <path d="M5 12.5l4.5 4.5L19 7" />
                      </svg>
                    )}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div className="t">{p.label}</div>
                    <div className="d">{p.source === 'perio_chart' ? 'From perio chart' : p.tooth ? 'Tooth #' + p.tooth : 'HITL draft'}</div>
                  </div>
                  <span className="chip">{p.status || 'draft'}</span>
                </div>
              ))}
            </div>
          ))}
          {plan.summary && (
            <div className="card tight">
              <h3>Plan narrative (from scribe)</h3>
              <pre style={{ marginTop: 8, whiteSpace: 'pre-wrap', fontSize: 12, color: 'var(--muted)' }}>{plan.summary}</pre>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

window.TreatmentPlan = TreatmentPlan;
