// Post-consultation summary — doctor writes Rx, patient sees saved outcome.

function postConsultParams() {
  const q = (window.location.hash.replace(/^#/, '') || '').split('?')[1] || '';
  return new URLSearchParams(q);
}

function PostConsult() {
  useDoctorReviews();
  const { user } = useAuth();
  const consults = useConsults();
  const params = postConsultParams();
  const consultId = params.get('consult') || '';
  const writeMode = params.get('write') === '1' || params.get('role') === 'doctor' || user?.role === 'doctor';
  const consult = consults.find((c) => c.id === consultId) || latestConsult();
  const doc = consult ? DOC_BY_ID(consult.docId) : DOC_BY_ID(1);

  if (writeMode) return <DoctorCloseConsult consult={consult} doc={doc}/>;
  return <PatientVisitSummary consult={consult} doc={doc}/>;
}

function DoctorCloseConsult({ consult, doc }) {
  const existing = consult?.prescription || {};
  const [form, setForm] = React.useState({
    diagnosis: existing.diagnosis || '',
    assessment: existing.assessment || '',
    medicines: existing.medicines || '',
    instructions: existing.instructions || '',
    followup: existing.followup || 'Follow-up online if pain persists or swelling increases.',
    referral: existing.referral || '',
  });
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const save = async () => {
    if (!consult?.id) { setErr('No consultation found.'); return; }
    setBusy(true); setErr('');
    const now = new Date().toISOString();
    const saved = await window.updateConsult(consult.id, {
      prescription: form,
      prescribed: true,
      completed: true,
      status: 'completed',
      followupRecommended: true,
      followupClosed: false,
      closedAt: now,
      endedAt: consult.endedAt || now,
    });
    setBusy(false);
    if (saved) window.navigate && window.navigate('/doctor-dashboard?tab=appointments');
    else setErr('Could not save prescription. Please try again.');
  };

  return (
    <PortalShell active="appointments" title="Close consultation" subtitle={`${consult?.patientName || 'Patient'} · ${consult?.id || ''}`}>
      <div style={{ padding: '24px 32px 48px', maxWidth: 1080, margin: '0 auto', display: 'grid', gridTemplateColumns: '1fr 320px', gap: 22 }}>
        <div className="ml-card" style={{ padding: 26 }}>
          <div className="ml-label" style={{ marginBottom: 14 }}>Prescription and treatment notes</div>
          <RxField label="Diagnosis" value={form.diagnosis} onChange={(v) => set('diagnosis', v)} placeholder="e.g. Suspected irreversible pulpitis / deep cavity"/>
          <RxField label="Clinical assessment" rows={3} value={form.assessment} onChange={(v) => set('assessment', v)} placeholder="Summarize symptoms, visible findings, and urgency."/>
          <RxField label="Medicine / prescription" rows={4} value={form.medicines} onChange={(v) => set('medicines', v)} placeholder="Medicine name, strength, dosage, duration, and safety notes."/>
          <RxField label="Care instructions" rows={3} value={form.instructions} onChange={(v) => set('instructions', v)} placeholder="Home care, diet, warning signs, and when to seek urgent in-clinic care."/>
          <RxField label="Follow-up plan" rows={2} value={form.followup} onChange={(v) => set('followup', v)} placeholder="Follow-up timing and whether online follow-up is suitable."/>
          <RxField label="Referral / clinic advice" rows={2} value={form.referral} onChange={(v) => set('referral', v)} placeholder="X-ray, root canal evaluation, extraction opinion, etc."/>

          {err && <div style={{ padding: 10, borderRadius: 8, background: 'oklch(96% 0.05 25)', color: 'var(--danger)', fontSize: 13, marginBottom: 12 }}>{err}</div>}
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
            <button className="ml-btn ml-btn--ghost" onClick={() => window.navigate && window.navigate('/doctor-dashboard')}>Save later</button>
            <button className="ml-btn ml-btn--primary" disabled={busy || !form.diagnosis.trim()} onClick={save}>
              {busy ? 'Saving...' : 'Save prescription & close'}
            </button>
          </div>
        </div>

        <aside className="ml-card" style={{ padding: 20, alignSelf: 'start' }}>
          <div className="ml-label" style={{ marginBottom: 12 }}>Consult details</div>
          <SummaryRow label="Patient" value={consult?.patientName || 'Patient'}/>
          <SummaryRow label="Reason" value={consult?.reason || 'Consultation'}/>
          <SummaryRow label="Pain" value={`${consult?.severity ?? '-'} / 10`}/>
          <SummaryRow label="Mode" value={consult?.mode || 'video'}/>
          <SummaryRow label="Time" value={`${consult?.date || ''} ${consult?.time || ''}`}/>
          {consult?.note && (
            <div style={{ marginTop: 14, padding: 12, borderRadius: 8, background: 'var(--paper-2)', fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>
              <div className="ml-label" style={{ marginBottom: 5 }}>Patient note</div>
              {consult.note}
            </div>
          )}
        </aside>
      </div>
    </PortalShell>
  );
}

function PatientVisitSummary({ consult, doc }) {
  const [rating, setRating] = React.useState(5);
  const [submitted, setSubmitted] = React.useState(false);
  const rx = consult?.prescription || null;
  const paidAt = consult?.paidAt ? new Date(consult.paidAt) : null;
  const followupFreeUntil = paidAt ? new Date(paidAt.getTime() + 7 * 24 * 60 * 60 * 1000) : null;
  const followupLabel = followupFreeUntil
    ? followupFreeUntil.toLocaleDateString('en-IN', { day: 'numeric', month: 'short' })
    : '7 days after payment';

  return (
    <PortalShell active="appointments" title="Visit summary" subtitle={consult ? `${consult.date || ''} · ${consult.time || ''}` : 'Your consultation summary'}>
      <div style={{ padding: '24px 32px', display: 'grid', gridTemplateColumns: '1fr 340px', gap: 24, maxWidth: 1200 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="ml-card" style={{ padding: 28, display: 'flex', gap: 20, alignItems: 'center', background: 'linear-gradient(135deg, var(--blue-soft), #fff)' }}>
            <div style={{ width: 56, height: 56, borderRadius: '50%', background: rx ? 'oklch(94% 0.07 165)' : 'var(--paper-2)', display: 'grid', placeItems: 'center' }}>
              {rx ? <I.check size={28} color="oklch(40% 0.13 165)"/> : <I.clock size={28} color="var(--ink-3)"/>}
            </div>
            <div>
              <h2 style={{ fontSize: 24, marginBottom: 4 }}>{rx ? 'Your dental summary is ready.' : 'Waiting for dentist notes.'}</h2>
              <p className="ml-muted" style={{ fontSize: 13.5, margin: 0 }}>
                {rx ? 'Prescription, medicine advice and follow-up plan are below.' : `${doc.n} will add the prescription and close the appointment shortly.`}
              </p>
            </div>
          </div>

          <div className="ml-card" style={{ padding: 24 }}>
            <div className="ml-label" style={{ marginBottom: 12 }}>Dentist's notes</div>
            <div style={{ display: 'grid', gridTemplateColumns: '130px 1fr', gap: 12, fontSize: 13.5 }}>
              <span className="ml-muted">Diagnosis</span><div>{rx?.diagnosis || 'Pending'}</div>
              <span className="ml-muted">Assessment</span><div>{rx?.assessment || 'Pending'}</div>
              <span className="ml-muted">Plan</span><div>{rx?.instructions || 'Pending'}</div>
              <span className="ml-muted">Referral</span><div>{rx?.referral || 'None added'}</div>
            </div>
          </div>

          <div className="ml-card" style={{ padding: 24 }}>
            <div className="ml-label" style={{ marginBottom: 12 }}>Prescription</div>
            <div style={{ padding: 16, background: 'var(--paper-2)', borderRadius: 8, whiteSpace: 'pre-wrap', fontSize: 13.5, lineHeight: 1.6 }}>
              {rx?.medicines || 'Prescription not added yet.'}
            </div>
            {rx?.followup && (
              <div style={{ marginTop: 14, padding: 14, borderRadius: 8, background: 'oklch(96% 0.04 165)', color: 'oklch(35% 0.10 165)', fontSize: 13 }}>
                <strong>Follow-up plan:</strong> {rx.followup}
              </div>
            )}
          </div>

          <div className="ml-card" style={{ padding: 24 }}>
            <div className="ml-label" style={{ marginBottom: 10 }}>How was your visit?</div>
            <div style={{ display: 'flex', gap: 6, marginBottom: 14 }}>
              {[1,2,3,4,5].map(n => (
                <I.star key={n} size={28} color={n <= rating ? 'oklch(75% 0.16 80)' : 'var(--line)'} style={{ cursor: 'pointer' }} onClick={() => setRating(n)}/>
              ))}
            </div>
            <button onClick={() => { window.submitDoctorReview && window.submitDoctorReview(doc.id, rating); setSubmitted(true); }} className="ml-btn ml-btn--primary" style={{ fontSize: 12.5 }}>
              {submitted ? 'Feedback saved' : 'Submit feedback'}
            </button>
          </div>
        </div>

        <aside style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div className="ml-card" style={{ padding: 18 }}>
            <div className="ml-label" style={{ marginBottom: 12 }}>Your dentist</div>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 12 }}>
              <div className="ml-avatar" style={{ width: 48, height: 48, borderRadius: '50%', fontSize: 16, background: TONE_BG[doc.tone], color: TONE_FG[doc.tone] }}>{doc.avatar}</div>
              <div>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{doc.n}</div>
                <div className="ml-muted" style={{ fontSize: 12 }}>{doc.spec} · {doc.creds}</div>
              </div>
            </div>
            <button onClick={() => window.navigate && window.navigate(`/book?doctor=${doc.id}&followup=1`)} className="ml-btn ml-btn--primary" style={{ fontSize: 12, padding: '8px 12px', width: '100%', justifyContent: 'center' }}>
              Book follow-up
            </button>
            <div className="ml-muted" style={{ fontSize: 11.5, lineHeight: 1.45, marginTop: 8 }}>
              Follow-up is free until {followupLabel}; after that, normal consultation charges apply.
            </div>
          </div>

          <div className="ml-card" style={{ padding: 18 }}>
            <div className="ml-label" style={{ marginBottom: 8 }}>Receipt</div>
            <SummaryRow label="Consultation fee" value={`₹${consult?.paidAmount || consult?.fee || doc.fee}`}/>
            <SummaryRow label="Status" value={consult?.paymentStatus === 'paid' ? 'Paid' : 'Pending'}/>
            <SummaryRow label="Visit ID" value={consult?.id || '-'}/>
          </div>
        </aside>
      </div>
    </PortalShell>
  );
}

function RxField({ label, value, onChange, placeholder, rows = 1 }) {
  return (
    <label style={{ display: 'block', marginBottom: 14 }}>
      <div className="ml-label" style={{ marginBottom: 6 }}>{label}</div>
      {rows > 1 ? (
        <textarea className="ml-input" rows={rows} value={value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} style={{ resize: 'vertical', fontFamily: 'var(--sans)' }}/>
      ) : (
        <input className="ml-input" value={value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)}/>
      )}
    </label>
  );
}

function SummaryRow({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '6px 0', fontSize: 13 }}>
      <span className="ml-muted">{label}</span>
      <span style={{ textAlign: 'right', color: 'var(--ink)' }}>{value}</span>
    </div>
  );
}

window.PostConsult = PostConsult;
