"use client";

import { useCallback, useEffect, useMemo, useState } from 'react';
import QRCode from 'qrcode';

const WA_SUBTABS = [
  ['pairing', 'Pairing', 'Bridge status + QR'],
  ['allowlist', 'Allowlist', 'Permitted senders'],
  ['messages', 'Messages', 'Inbound + outbound'],
  ['send', 'Send', 'Manual message'],
];

function pairingTone(state) {
  if (state === 'paired') return 'ready';
  if (state === 'qr_required' || state === 'reconnecting' || state === 'starting') return 'warn';
  return 'danger';
}

function pairingLabel(state) {
  if (state === 'paired') return 'Connected';
  if (state === 'qr_required') return 'Awaiting QR scan';
  if (state === 'reconnecting') return 'Reconnecting';
  if (state === 'logged_out') return 'Logged out — reset session';
  if (state === 'starting') return 'Starting';
  return 'Bridge offline';
}

async function fetchJson(url, opts) {
  const res = await fetch(url, opts);
  const text = await res.text();
  try { return { ok: res.ok, status: res.status, json: text ? JSON.parse(text) : null }; }
  catch { return { ok: res.ok, status: res.status, json: null, text }; }
}

export default function WhatsAppSection() {
  const [waSub, setWaSub] = useState('pairing');
  const [status, setStatus] = useState(null);
  const [qr, setQr] = useState(null);
  const [qrDataUrl, setQrDataUrl] = useState('');
  const [messages, setMessages] = useState([]);
  const [err, setErr] = useState(null);

  // Allowlist add form state
  const [addChatId, setAddChatId] = useState('');
  const [addLabel, setAddLabel] = useState('');
  const [addBusy, setAddBusy] = useState(false);
  const [addError, setAddError] = useState('');
  const [removingId, setRemovingId] = useState(null);

  // Disconnect state
  const [disconnectBusy, setDisconnectBusy] = useState(false);
  const [confirmDisconnect, setConfirmDisconnect] = useState(false);

  // Send form state
  const [sendChatId, setSendChatId] = useState('');
  const [sendText, setSendText] = useState('');
  const [sendBusy, setSendBusy] = useState(false);
  const [sendError, setSendError] = useState('');
  const [sendOk, setSendOk] = useState(false);

  const refreshAll = useCallback(async () => {
    try {
      const [s, q, m] = await Promise.all([
        fetchJson('/api/whatsapp/status'),
        fetchJson('/api/whatsapp/qr'),
        fetchJson('/api/whatsapp/messages?limit=50'),
      ]);
      setStatus(s.json);
      setQr(q.json);
      setMessages(m.json?.messages || []);
      setErr(null);
    } catch (e) {
      setErr(e.message);
    }
  }, []);

  useEffect(() => {
    refreshAll();
    const t = setInterval(refreshAll, 3500);
    return () => clearInterval(t);
  }, [refreshAll]);

  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: 220, errorCorrectionLevel: 'M' });
        if (!cancelled) setQrDataUrl(dataUrl);
      } catch {
        if (!cancelled) setQrDataUrl('');
      }
    }
    render();
    return () => { cancelled = true; };
  }, [qr]);

  const health = status?.health || {};
  const allowlist = status?.allowlist || [];
  const pairingState = health.pairing_state || (health.ok === false ? 'offline' : 'unknown');
  const showQrCard = pairingState !== 'paired';
  const lastConnected = health.last_connected_at
    ? new Date(health.last_connected_at).toLocaleTimeString()
    : '—';

  const dedicatedNumberWarning = useMemo(() => (
    <p className="whatsapp-warn-copy">
      Pair only a dedicated WhatsApp number, not your personal account. Baileys is an unofficial WhatsApp Web client and the paired account can be banned.
    </p>
  ), []);

  async function handleAddAllow(e) {
    e.preventDefault();
    if (!addChatId.trim()) return;
    setAddBusy(true);
    setAddError('');
    const r = await fetchJson('/api/whatsapp/allowlist', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ chat_id: addChatId.trim(), label: addLabel.trim() || null }),
    });
    setAddBusy(false);
    if (!r.ok) {
      setAddError(r.json?.error || 'Failed to add');
      return;
    }
    setAddChatId('');
    setAddLabel('');
    refreshAll();
  }

  async function handleRemoveAllow(chatId) {
    setRemovingId(chatId);
    const r = await fetchJson(`/api/whatsapp/allowlist?chat_id=${encodeURIComponent(chatId)}`, { method: 'DELETE' });
    setRemovingId(null);
    if (!r.ok) setErr(r.json?.error || 'Failed to remove');
    else refreshAll();
  }

  async function handleDisconnect() {
    setDisconnectBusy(true);
    setErr(null);
    const r = await fetchJson('/api/whatsapp/disconnect', { method: 'POST' });
    setDisconnectBusy(false);
    setConfirmDisconnect(false);
    if (!r.ok) {
      setErr(r.json?.error || 'Failed to disconnect');
      return;
    }
    refreshAll();
  }

  async function handleSend(e) {
    e.preventDefault();
    if (!sendChatId.trim() || !sendText.trim()) return;
    setSendBusy(true);
    setSendError('');
    setSendOk(false);
    const r = await fetchJson('/api/whatsapp/send', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ chat_id: sendChatId.trim(), text: sendText.trim() }),
    });
    setSendBusy(false);
    if (!r.ok) {
      setSendError(r.json?.error || 'Failed to send');
      return;
    }
    setSendText('');
    setSendOk(true);
    refreshAll();
  }

  return (
    <div className="wa-section">
      {/* Status pill row */}
      <div className="wa-status-row">
        <span className={`admin-pill ${pairingTone(pairingState)}`}>
          {pairingLabel(pairingState)}
        </span>
        {health.user && (
          <span className="wa-status-user">{health.user}</span>
        )}
      </div>

      {err && (
        <div className="wa-error-banner">{err}</div>
      )}

      {/* Subnav — same pattern as tools-subnav in config-panel */}
      <nav className="tools-subnav" role="tablist" aria-label="WhatsApp sections">
        {WA_SUBTABS.map(([id, label, desc]) => (
          <button
            key={id}
            type="button"
            role="tab"
            aria-selected={waSub === id}
            className={'tools-subnav-pill' + (waSub === id ? ' on' : '')}
            onClick={() => setWaSub(id)}
          >
            <b>{label}</b>
            <small>{desc}</small>
          </button>
        ))}
      </nav>

      {/* ── Pairing tab ── */}
      {waSub === 'pairing' && (
        <div className="tools-pane">
          <div className="wa-stats-row">
            <div className="wa-stat"><span className="wa-stat-label">Paired account</span><span className="wa-stat-value">{health.user || '—'}</span></div>
            <div className="wa-stat"><span className="wa-stat-label">Bridge queue</span><span className="wa-stat-value">{health.queue_size ?? 0}</span></div>
            <div className="wa-stat"><span className="wa-stat-label">Last connected</span><span className="wa-stat-value">{lastConnected}</span></div>
          </div>

          {health.last_error && (
            <div className="wa-error-banner">{health.last_error}</div>
          )}

          {showQrCard ? (
            <div className="config-secrets-panel" style={{ marginTop: 0 }}>
              <div className="config-secrets-head">
                <div>
                  <span className="config-section-title">
                    {pairingState === 'logged_out' ? 'Session logged out' : 'Pair device'}
                  </span>
                  <p>
                    {pairingState === 'logged_out'
                      ? 'WhatsApp unlinked this device server-side, so the stale credentials block a fresh QR. Reset the session to wipe them and generate a new pairing code.'
                      : 'Open WhatsApp → Settings → Linked Devices → Link a Device, then scan the code.'}
                  </p>
                </div>
                {pairingState === 'logged_out' && (
                  !confirmDisconnect ? (
                    <button
                      type="button"
                      className="secrets-action-btn danger"
                      onClick={() => setConfirmDisconnect(true)}
                      disabled={disconnectBusy}
                    >
                      Reset session
                    </button>
                  ) : (
                    <div className="wa-disconnect-confirm">
                      <button
                        type="button"
                        className="secrets-action-btn danger"
                        onClick={handleDisconnect}
                        disabled={disconnectBusy}
                      >
                        {disconnectBusy ? 'Resetting…' : 'Confirm reset'}
                      </button>
                      <button
                        type="button"
                        className="secrets-action-btn"
                        onClick={() => setConfirmDisconnect(false)}
                        disabled={disconnectBusy}
                      >
                        Cancel
                      </button>
                    </div>
                  )
                )}
              </div>
              {pairingState === 'logged_out' ? (
                <div className="whatsapp-pair-copy">{dedicatedNumberWarning}</div>
              ) : (
                <div className="whatsapp-pair-row">
                  {qrDataUrl ? (
                    <div className="whatsapp-qr-box">
                      <img src={qrDataUrl} alt="WhatsApp pairing QR code" width={220} height={220} />
                    </div>
                  ) : (
                    <div className="whatsapp-qr-pending">Waiting for QR — make sure the daemon is running.</div>
                  )}
                  <div className="whatsapp-pair-copy">
                    <p>Code rotates roughly every 20 seconds. The dashboard re-fetches automatically. The session is saved at <code>data/whatsapp/session/</code>.</p>
                    {dedicatedNumberWarning}
                  </div>
                </div>
              )}
            </div>
          ) : (
            <div className="config-secrets-panel" style={{ marginTop: 0 }}>
              <div className="config-secrets-head">
                <div>
                  <span className="config-section-title">Bridge is paired</span>
                  <p>The WhatsApp session is active. Allowlisted senders can message this agent directly.</p>
                </div>
                {!confirmDisconnect ? (
                  <button
                    type="button"
                    className="secrets-action-btn danger"
                    onClick={() => setConfirmDisconnect(true)}
                    disabled={disconnectBusy}
                  >
                    Disconnect
                  </button>
                ) : (
                  <div className="wa-disconnect-confirm">
                    <button
                      type="button"
                      className="secrets-action-btn danger"
                      onClick={handleDisconnect}
                      disabled={disconnectBusy}
                    >
                      {disconnectBusy ? 'Disconnecting...' : 'Confirm disconnect'}
                    </button>
                    <button
                      type="button"
                      className="secrets-action-btn"
                      onClick={() => setConfirmDisconnect(false)}
                      disabled={disconnectBusy}
                    >
                      Cancel
                    </button>
                  </div>
                )}
              </div>
              {confirmDisconnect && (
                <p className="whatsapp-warn-copy">
                  Unlinks this device from WhatsApp and wipes the local session. You will need to scan a new QR code to reconnect.
                </p>
              )}
              {dedicatedNumberWarning}
            </div>
          )}
        </div>
      )}

      {/* ── Allowlist tab ── */}
      {waSub === 'allowlist' && (
        <div className="tools-pane">
          <div className="config-secrets-panel">
            <div className="config-secrets-head">
              <div>
                <span className="config-section-title">Allowed senders</span>
                <p>Only chats on this list can message the agent. Add new entries below.</p>
              </div>
            </div>

            {/* Inline add form — no modal */}
            <form className="secrets-add-form" onSubmit={handleAddAllow}>
              <div className="secrets-add-fields">
                <label className="config-env-field">
                  <span className="config-env-field-top"><b>Chat id</b></span>
                  <input
                    type="text"
                    autoComplete="off"
                    placeholder="9715XXXXXXXX or full JID"
                    value={addChatId}
                    onChange={e => setAddChatId(e.target.value)}
                    required
                  />
                </label>
                <label className="config-env-field">
                  <span className="config-env-field-top">
                    <b>Label</b>
                    <em style={{ fontStyle: 'normal', fontSize: '10px', color: '#68707b', background: 'transparent', padding: 0 }}>optional</em>
                  </span>
                  <input
                    type="text"
                    autoComplete="off"
                    placeholder="e.g. Founder phone"
                    value={addLabel}
                    onChange={e => setAddLabel(e.target.value)}
                  />
                </label>
              </div>
              <div className="secrets-add-footer">
                {addError && <span className="secrets-error">{addError}</span>}
                <button
                  type="submit"
                  className="config-save-btn"
                  disabled={addBusy || !addChatId.trim()}
                >
                  {addBusy ? 'Adding...' : 'Add to allowlist'}
                </button>
              </div>
            </form>

            {allowlist.length === 0 ? (
              <div className="allowlists-entries-empty">
                No senders allowlisted — all inbound messages are dropped.
                Add at least one chat id above.
              </div>
            ) : (
              <div className="config-tools-list">
                {allowlist.map(row => (
                  <div key={row.chat_id} className="config-tool-row on">
                    <div className="secrets-row-inner">
                      <div className="secrets-row-meta">
                        <div className="config-tool-titleline">
                          <span className="config-tool-name" style={{ textTransform: 'none' }}>
                            <code className="whatsapp-mono">{row.chat_id}</code>
                          </span>
                          {row.kind && <span className="config-tool-risk">{row.kind}</span>}
                        </div>
                        {(row.label || row.created_at) && (
                          <div className="config-tool-status">
                            {row.label && <span>{row.label}</span>}
                            {row.created_at && <span>{new Date(row.created_at).toLocaleString()}</span>}
                          </div>
                        )}
                      </div>
                      <div className="secrets-row-actions">
                        <button
                          type="button"
                          className="secrets-action-btn danger"
                          disabled={removingId === row.chat_id}
                          onClick={() => handleRemoveAllow(row.chat_id)}
                        >
                          {removingId === row.chat_id ? '...' : 'Remove'}
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      )}

      {/* ── Messages tab ── */}
      {waSub === 'messages' && (
        <div className="tools-pane">
          <div className="config-secrets-panel">
            <div className="config-secrets-head">
              <div>
                <span className="config-section-title">Recent messages</span>
                <p>{messages.length} of last 50 inbound + outbound.</p>
              </div>
            </div>
            {messages.length === 0 ? (
              <div className="secrets-empty">No messages yet. Inbound and outbound traffic from the bridge will appear here.</div>
            ) : (
              <div style={{ overflowX: 'auto' }}>
                <table className="admin-table" style={{ minWidth: 520 }}>
                  <thead>
                    <tr>
                      <th>When</th>
                      <th>Dir</th>
                      <th>Chat</th>
                      <th>Sender</th>
                      <th>Text</th>
                    </tr>
                  </thead>
                  <tbody>
                    {messages.map(row => (
                      <tr key={row.id}>
                        <td style={{ whiteSpace: 'nowrap' }}>{new Date(row.created_at).toLocaleTimeString()}</td>
                        <td>
                          <span className={`admin-pill ${row.direction === 'inbound' ? 'warn' : 'ready'}`}>
                            {row.direction}
                          </span>
                        </td>
                        <td><code className="whatsapp-mono">{row.chat_id}</code></td>
                        <td><code className="whatsapp-mono">{row.sender || '—'}</code></td>
                        <td style={{ maxWidth: 260, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                          {row.text}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      )}

      {/* ── Send tab ── */}
      {waSub === 'send' && (
        <div className="tools-pane">
          <div className="config-secrets-panel">
            <div className="config-secrets-head">
              <div>
                <span className="config-section-title">Send a message</span>
                <p>Manual outbound send. Logs to whatsapp_messages with an audit row.</p>
              </div>
            </div>
            <form className="secrets-add-form" onSubmit={handleSend}>
              <div className="secrets-add-fields">
                <label className="config-env-field">
                  <span className="config-env-field-top"><b>Chat id</b></span>
                  <input
                    type="text"
                    autoComplete="off"
                    placeholder="Digits or full JID"
                    value={sendChatId}
                    onChange={e => { setSendChatId(e.target.value); setSendOk(false); }}
                    required
                  />
                </label>
                <label className="config-env-field">
                  <span className="config-env-field-top"><b>Message</b></span>
                  <textarea
                    rows={4}
                    placeholder="Plain text only"
                    value={sendText}
                    onChange={e => { setSendText(e.target.value); setSendOk(false); }}
                    required
                    style={{ resize: 'vertical', fontFamily: 'inherit', fontSize: '13px', padding: '8px 10px', borderRadius: 8, border: '1px solid rgba(17,19,24,.12)', outline: 'none', width: '100%', boxSizing: 'border-box' }}
                  />
                </label>
              </div>
              <div className="secrets-add-footer">
                {sendError && <span className="secrets-error">{sendError}</span>}
                {sendOk && <span style={{ fontSize: 12, color: '#2d7044', fontWeight: 650 }}>Sent</span>}
                <button
                  type="submit"
                  className="config-save-btn"
                  disabled={sendBusy || !sendChatId.trim() || !sendText.trim()}
                >
                  {sendBusy ? 'Sending...' : 'Send message'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
