// Dummy checkout. This accepts test payment details only and marks the consult
// paid for demo/testing. No real money is charged.

function PayCheckout({ tone = 'warm', route = '' }) {
  const { user } = useAuth();
  const consults = useConsults();
  const [params] = React.useState(() => new URLSearchParams((route.split('?')[1] || '')));
  const consultId = params.get('consult') || '';
  const emergency = params.get('emergency') === '1';
  const [emergencyConsult, setEmergencyConsult] = React.useState(null);
  const [syncedOnce, setSyncedOnce] = React.useState(false);
  const creatingEmergency = React.useRef(false);
  const consult = emergencyConsult || consults.find((c) => c.id === consultId) || (!emergency ? consults[0] : null);
  const doc = consult ? DOC_BY_ID(consult.docId) : DOC_BY_ID(1);

  const [method, setMethod] = React.useState('upi');
  const [upi, setUpi] = React.useState('patient@upi');
  const [card, setCard] = React.useState({ number: '4111 1111 1111 1111', name: user?.name || 'Test Patient', exp: '12/28', cvv: '123' });
  const [bank, setBank] = React.useState('HDFC Bank');
  const [wallet, setWallet] = React.useState('Paytm');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const fee = consult?.fee ?? doc.fee;
  const tax = Math.round(fee * 0.0);
  const total = fee + tax;

  React.useEffect(() => {
    if (!emergency || consult || creatingEmergency.current) return;
    creatingEmergency.current = true;
    (async () => {
      const created = await (window.createConsult && window.createConsult({
        docId: 1,
        reason: 'Emergency dental consultation 24/7',
        severity: 8,
        mode: 'video',
        selectedDay: 'Today',
        slot: 'Immediate',
        time: 'Immediate',
        fee: DOC_BY_ID(1).fee,
        paymentStatus: 'pending',
        careType: 'Emergency 24/7',
        note: 'Emergency consultation',
        patientName: user?.name || 'New patient',
        patientInitials: user?.initials || 'PT',
      }));
      if (created) setEmergencyConsult(created);
      creatingEmergency.current = false;
    })();
  }, [emergency, consult, user?.userId]);
  React.useEffect(() => {
    if (!consultId || consult || syncedOnce || !window.syncConsultsFromServer) return;
    let cancelled = false;
    (async () => {
      await window.syncConsultsFromServer();
      if (!cancelled) setSyncedOnce(true);
    })();
    return () => { cancelled = true; };
  }, [consultId, !!consult, syncedOnce]);

  const submit = async () => {
    let payableConsult = consult;
    if (!payableConsult && window.syncConsultsFromServer) {
      const fresh = await window.syncConsultsFromServer();
      payableConsult = (fresh || []).find((c) => c.id === consultId) || (fresh || [])[0] || null;
    }
    if (!payableConsult) { setErr('No consult to pay for. Please go back and confirm the appointment again.'); return; }
    const ref = dummyPaymentRef(method, { upi, card, bank, wallet });
    if (!ref.ok) { setErr(ref.error); return; }

    setBusy(true);
    setErr('');
    const saved = await (window.chargeConsult && window.chargeConsult({
      consultId: payableConsult.id,
      amount: total,
      last4: ref.value,
      method,
    }));
    setBusy(false);

    if (saved) {
      await (window.syncConsultsFromServer && window.syncConsultsFromServer());
      window.navigate && window.navigate('/confirmed?consult=' + encodeURIComponent(payableConsult.id));
    } else {
      setErr("We couldn't mark this dummy payment paid. Try again.");
    }
  };

  return (
    <PortalShell active="appointments" title="Dummy checkout" subtitle="Use test details only. No real money is charged.">
      <div style={{ padding: '24px 32px 48px', maxWidth: 1080, margin: '0 auto', display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 22 }}>

        <div className="ml-card" style={{ padding: 28 }}>
          <div className="ml-label" style={{ marginBottom: 12 }}>TEST PAYMENT METHOD</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginBottom: 20 }}>
            {[
              { k: 'upi', label: 'UPI', sub: 'Dummy VPA' },
              { k: 'card', label: 'Card', sub: 'Test card' },
              { k: 'netbanking', label: 'Net banking', sub: 'Demo bank' },
              { k: 'wallet', label: 'Wallet', sub: 'Demo wallet' },
            ].map((m) => (
              <button key={m.k} onClick={() => { setMethod(m.k); setErr(''); }} className="ml-card" style={{
                padding: 12,
                textAlign: 'left',
                cursor: 'pointer',
                border: '1.5px solid ' + (method === m.k ? 'var(--blue)' : 'var(--line)'),
                background: method === m.k ? 'var(--blue-tint)' : '#fff',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 600 }}>
                  <I.card size={14} color={method === m.k ? 'var(--blue-deep)' : 'var(--ink-3)'}/>
                  {m.label}
                </div>
                <div className="ml-muted" style={{ fontSize: 11, marginTop: 4 }}>{m.sub}</div>
              </button>
            ))}
          </div>

          {method === 'upi' && (
            <Field label="Dummy UPI ID">
              <input value={upi} onChange={(e) => setUpi(e.target.value)} className="ml-input" placeholder="patient@upi"/>
            </Field>
          )}

          {method === 'card' && (
            <>
              <Field label="Dummy card number">
                <input value={card.number} onChange={(e) => setCard({ ...card, number: e.target.value })}
                  className="ml-input" inputMode="numeric" placeholder="4111 1111 1111 1111" style={{ letterSpacing: '0.04em' }}/>
              </Field>
              <Field label="Cardholder name">
                <input value={card.name} onChange={(e) => setCard({ ...card, name: e.target.value })}
                  className="ml-input" placeholder="Test Patient"/>
              </Field>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <Field label="Expiry">
                  <input value={card.exp} onChange={(e) => setCard({ ...card, exp: e.target.value })}
                    className="ml-input" placeholder="12/28"/>
                </Field>
                <Field label="CVV">
                  <input value={card.cvv} onChange={(e) => setCard({ ...card, cvv: e.target.value })}
                    className="ml-input" inputMode="numeric" maxLength={4} placeholder="123"/>
                </Field>
              </div>
            </>
          )}

          {method === 'netbanking' && (
            <Field label="Dummy bank">
              <select value={bank} onChange={(e) => setBank(e.target.value)} className="ml-input">
                {['HDFC Bank', 'ICICI Bank', 'State Bank of India', 'Axis Bank', 'Kotak Mahindra Bank', 'Yes Bank'].map((b) => <option key={b}>{b}</option>)}
              </select>
            </Field>
          )}

          {method === 'wallet' && (
            <Field label="Dummy wallet">
              <select value={wallet} onChange={(e) => setWallet(e.target.value)} className="ml-input">
                {['Paytm', 'Amazon Pay', 'PhonePe Wallet', 'Mobikwik'].map((w) => <option key={w}>{w}</option>)}
              </select>
            </Field>
          )}

          <div style={{ padding: 16, borderRadius: 12, border: '1px dashed var(--line-2)', background: 'var(--paper-2)', display: 'grid', gridTemplateColumns: '92px 1fr', gap: 14, alignItems: 'center', marginBottom: 12 }}>
            <div style={{ width: 92, height: 92, borderRadius: 8, background: '#fff', display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 3, padding: 8 }}>
              {Array.from({ length: 25 }).map((_, i) => <span key={i} style={{ background: (i * 7) % 5 < 2 ? 'var(--ink)' : 'transparent', borderRadius: 1 }}/>)}
            </div>
            <div>
              <div style={{ fontWeight: 600, marginBottom: 4 }}>Dummy payment mode</div>
              <div className="ml-muted" style={{ fontSize: 12, lineHeight: 1.5 }}>
                These details are for testing only. The appointment is marked paid in Molara, but no payment gateway is contacted.
              </div>
            </div>
          </div>

          {err && (
            <div style={{ marginTop: 12, padding: '10px 12px', borderRadius: 8, background: 'oklch(95% 0.05 25)', color: 'oklch(40% 0.14 25)', fontSize: 13 }}>
              {err}
            </div>
          )}

          <button onClick={submit} disabled={busy || !consult}
            className="ml-btn ml-btn--primary" style={{ marginTop: 18, padding: '12px 22px', width: '100%', justifyContent: 'center' }}>
            {busy ? 'Processing...' : <><I.lock size={13}/> Confirm dummy payment of ₹{total}</>}
          </button>
          <div className="ml-muted" style={{ fontSize: 11.5, marginTop: 10, textAlign: 'center' }}>
            Dummy payment only. No real charge.
          </div>
        </div>

        <div className="ml-card" style={{ padding: 24, alignSelf: 'start' }}>
          <div className="ml-label" style={{ marginBottom: 14 }}>ORDER SUMMARY</div>

          {consult ? (
            <>
              <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 16 }}>
                <div className="ml-avatar" style={{
                  width: 52, height: 52, borderRadius: 12, fontSize: 18,
                  background: TONE_BG[doc.tone], color: TONE_FG[doc.tone],
                }}>{doc.avatar}</div>
                <div>
                  <div style={{ fontFamily: 'var(--display)', fontSize: 16, fontWeight: 500 }}>{doc.n}</div>
                  <div className="ml-muted" style={{ fontSize: 12 }}>{doc.spec}</div>
                </div>
              </div>

              <Row label="Visit ID" value={<span style={{ fontFamily: 'var(--mono)', fontSize: 12 }}>{consult.id}</span>}/>
              <Row label="Date & time" value={`${consult.date} · ${consult.time}`}/>
              <Row label="Platform" value={window.bookingModeLabel ? window.bookingModeLabel(consult.mode) : 'WhatsApp consultation'}/>
              <Row label="Reason" value={consult.reason || 'Dental consultation'}/>

              <hr className="ml-hr" style={{ margin: '14px 0' }}/>

              <Row label="Consultation fee" value={`₹${fee}`}/>
              <Row label="Platform tax" value={`₹${tax}`}/>
              <Row label={<span style={{ fontWeight: 600, color: 'var(--ink)' }}>Total</span>}
                   value={<span style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 16 }}>₹{total}</span>}/>

              <div style={{ marginTop: 16, padding: 12, borderRadius: 10, background: 'oklch(96% 0.04 165)', fontSize: 12, color: 'oklch(35% 0.10 165)', lineHeight: 1.5 }}>
                <strong>Free follow-up:</strong> Once marked paid, the patient can book 1 follow-up with {doc.n.split(' ').slice(0, 2).join(' ')} within 7 days at no extra cost for the same or lower consult mode.
              </div>
            </>
          ) : (
            <div className="ml-muted" style={{ fontSize: 13 }}>
              {emergency ? 'Preparing your 24/7 emergency consult with Dr. Shivani...' : 'No consult selected.'}
            </div>
          )}
        </div>
      </div>
    </PortalShell>
  );
}

function dummyPaymentRef(method, { upi, card, bank, wallet }) {
  if (method === 'upi') {
    const clean = String(upi || '').trim();
    if (!clean || !clean.includes('@')) return { ok: false, error: 'Enter a dummy UPI ID, for example patient@upi.' };
    return { ok: true, value: clean.slice(-12) };
  }
  if (method === 'card') {
    const digits = String(card.number || '').replace(/\D/g, '');
    if (digits.length < 12) return { ok: false, error: 'Enter a dummy card number.' };
    if (String(card.cvv || '').replace(/\D/g, '').length < 3) return { ok: false, error: 'Enter a dummy CVV.' };
    return { ok: true, value: digits.slice(-4) };
  }
  if (method === 'netbanking') return { ok: true, value: bank || 'demo-bank' };
  if (method === 'wallet') return { ok: true, value: wallet || 'demo-wallet' };
  return { ok: true, value: 'demo' };
}

function Field({ label, children }) {
  return (
    <label style={{ display: 'block', marginBottom: 12 }}>
      <div className="ml-label" style={{ marginBottom: 6, fontSize: 11 }}>{label.toUpperCase()}</div>
      {children}
    </label>
  );
}

function Row({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 13.5, color: 'var(--ink-2)' }}>
      <span>{label}</span>
      <span style={{ color: 'var(--ink)', textAlign: 'right' }}>{value}</span>
    </div>
  );
}

Object.assign(window, { PayCheckout });
