'use client';

import * as React from 'react';
import QRCode from 'qrcode';

/**
 * WhatsApp pairing step. Polls /api/whatsapp/qr + /api/whatsapp/status every
 * 3.5s (matches the existing /whatsapp page). When the bridge reports paired,
 * automatically advances by calling onPaired().
 */
export default function QrPairStep({ connection, onPaired }) {
  const [qr, setQr] = React.useState(null);
  const [health, setHealth] = React.useState(null);
  const [qrDataUrl, setQrDataUrl] = React.useState('');
  const [bridgeReachable, setBridgeReachable] = React.useState(null);
  const pairedRef = React.useRef(false);

  React.useEffect(() => {
    let cancelled = false;
    async function tick() {
      try {
        const [qres, sres] = await Promise.all([
          fetch('/api/whatsapp/qr').then(r => r.json()).catch(() => null),
          fetch('/api/whatsapp/status').then(r => r.json()).catch(() => null),
        ]);
        if (cancelled) return;
        setQr(qres || null);
        setHealth(sres?.health || null);
        setBridgeReachable(sres ? Boolean(sres?.health) : false);
        const paired = qres?.paired || sres?.health?.pairing_state === 'paired';
        if (paired && !pairedRef.current) {
          pairedRef.current = true;
          onPaired();
        }
      } catch {
        if (!cancelled) setBridgeReachable(false);
      }
    }
    tick();
    const interval = setInterval(tick, 3500);
    return () => {
      cancelled = true;
      clearInterval(interval);
    };
  }, [onPaired]);

  React.useEffect(() => {
    let cancelled = false;
    async function render() {
      if (qr?.paired || !qr?.qr) {
        setQrDataUrl('');
        return;
      }
      try {
        const dataUrl = await QRCode.toDataURL(qr.qr, { margin: 1, width: 240, errorCorrectionLevel: 'M' });
        if (!cancelled) setQrDataUrl(dataUrl);
      } catch {
        if (!cancelled) setQrDataUrl('');
      }
    }
    render();
    return () => { cancelled = true; };
  }, [qr]);

  const pairingState = health?.pairing_state || (bridgeReachable === false ? 'offline' : 'starting');
  const daemonCommand = connection?.connection?.requires_daemon || 'npm run whatsapp:bridge';
  const bridgeDown = bridgeReachable === false || pairingState === 'offline';

  return (
    <section className="connection-setup-step connection-setup-step-qr">
      <p className="connection-setup-intro">
        Open WhatsApp on your phone → <b>Settings</b> → <b>Linked Devices</b> → <b>Link a Device</b>,
        then scan the code below. Madarx will receive incoming WhatsApp messages through this number.
      </p>

      {bridgeDown ? (
        <div className="connection-setup-warning">
          <p>The WhatsApp bridge daemon is not running.</p>
          <p>
            Run <code>{daemonCommand}</code> in a terminal, then return to this screen. The
            QR code will appear automatically once the daemon is up.
          </p>
        </div>
      ) : null}

      <div className="connection-setup-qr-row">
        {qrDataUrl ? (
          <div className="connection-setup-qr-box">
            <img src={qrDataUrl} alt="WhatsApp pairing QR code" width={240} height={240} />
          </div>
        ) : pairingState === 'paired' ? (
          <div className="connection-setup-qr-pending">Paired — finishing up…</div>
        ) : (
          <div className="connection-setup-qr-pending">
            {bridgeDown ? 'Waiting for the daemon…' : 'Waiting for QR…'}
          </div>
        )}
        <div className="connection-setup-qr-copy">
          <p>
            Pair only a <b>dedicated WhatsApp number</b>, not your personal account. Baileys
            is an unofficial Web client and the paired account can be banned.
          </p>
          <p className="connection-setup-qr-status">
            <span className={`connection-status ${pairingState === 'paired' ? 'connected' : 'needs_setup'}`}>
              {pairingState === 'paired' ? 'Paired' : pairingState === 'qr_required' ? 'Awaiting scan' : pairingState}
            </span>
          </p>
        </div>
      </div>
    </section>
  );
}
