import { useState, useEffect } from 'react'
import { useWaste } from '../store'

interface Props {
  status: 'disconnected' | 'connecting' | 'connected'
}

// Parse URL search params for pre-filling the join form.
// Supports:
//   ?invite=waste:<b64>   waste: invite string (anchor + network name + net hash)
//   ?n=<name>             network name shorthand
//   ?network=<name>       network name
//   ?net=<64hex>          yaw2-style full network hash (joined without plaintext name)
//   ?a=<url>              anchor URL hint (informational — daemon controls its anchor)
function parseInviteParams(): { network: string; netHash: string; anchor: string; inviteString: string } {
  const p = new URLSearchParams(window.location.search)
  const inviteString = p.get('invite') ?? ''
  let network = p.get('n') ?? p.get('network') ?? ''
  let netHash = p.get('net') ?? ''
  let anchor = p.get('a') ?? p.get('anchor') ?? ''

  if (inviteString.startsWith('waste:')) {
    try {
      // URL-safe base64 → standard base64
      const json = JSON.parse(atob(inviteString.slice(6).replace(/-/g, '+').replace(/_/g, '/')))
      network = network || json.network || ''
      netHash = netHash || json.net || ''
      anchor = anchor || json.anchor || ''
    } catch { /* ignore bad invite */ }
  }

  // URL path: /<16hex>/ — short network ID from anchor-served URL
  const pathMatch = window.location.pathname.match(/\/([0-9a-f]{16})\/?$/i)
  if (pathMatch && !netHash && !network) {
    // Only the short ID — can't join by short ID alone (need full hash for HKDF).
    // Store it as a hint; the user must supply the network name OR a full 64-char hash.
  }

  return { network, netHash, anchor, inviteString }
}

export function Onboarding({ status }: Props) {
  const { send, masterAlias, masterId, exportedBackup } = useWaste()
  const [network, setNetwork] = useState('')
  const [netHash, setNetHash] = useState('')
  const [inviteString, setInviteString] = useState('')
  const [anchorHint, setAnchorHint] = useState('')
  const [exportPass, setExportPass] = useState('')
  const [importJson, setImportJson] = useState('')
  const [importPass, setImportPass] = useState('')
  const [importStatus, setImportStatus] = useState('')
  const [showBackup, setShowBackup] = useState(false)

  useEffect(() => {
    const { network: n, netHash: nh, anchor: a, inviteString: inv } = parseInviteParams()
    if (n) setNetwork(n)
    if (nh) setNetHash(nh)
    if (a) setAnchorHint(a)
    if (inv) setInviteString(inv)
  }, [])

  function joinNetwork(e: React.FormEvent) {
    e.preventDefault()
    const name = network.trim()
    const hash = netHash.trim()
    if (!name && !hash) return
    if (hash.length === 64 && !name) {
      // yaw2-style: join by full network hash without plaintext name
      send({ type: 'join_network', network_hash: hash })
    } else {
      send({ type: 'join_network', network_name: name })
    }
  }

  function exportIdentity(e: React.FormEvent) {
    e.preventDefault()
    if (!exportPass.trim()) return
    setExportBlob('')
    send({ type: 'export_identity', passphrase: exportPass })
  }

  function importIdentity(e: React.FormEvent) {
    e.preventDefault()
    if (!importJson.trim() || !importPass.trim()) return
    setImportStatus('Verifying…')
    send({ type: 'import_identity', backup: importJson, passphrase: importPass })
  }

  const shortId = masterId ? masterId.slice(0, 16).replace(/(.{4})/g, '$1 ').trim() : null

  // ── disconnected / connecting ────────────────────────────────────────────────
  if (status !== 'connected') {
    return (
      <div className="onboarding">
        <h1>waste</h1>
        {status === 'connecting' ? (
          <p className="status connecting">Connecting to daemon…</p>
        ) : (
          <>
            <p className="status disconnected">Daemon not running</p>
            <p className="onboarding-hint">
              Start the daemon to use the web UI:
            </p>
            <pre className="onboarding-code">./launch-web.sh</pre>
            <p className="onboarding-hint muted">
              Or pass a custom alias and network:
            </p>
            <pre className="onboarding-code">ALIAS=alice NETWORK=friends ./launch-web.sh</pre>
          </>
        )}
      </div>
    )
  }

  // ── connected — join form ────────────────────────────────────────────────────
  return (
    <div className="onboarding">
      <h1>waste</h1>

      {masterAlias && (
        <div className="onboarding-identity">
          <span className="alias">{masterAlias}</span>
          {shortId && <span className="peer-id mono">{shortId}</span>}
        </div>
      )}

      <form onSubmit={joinNetwork} className="join-form">
        <label className="join-label">Join a network</label>
        {anchorHint && (
          <p className="onboarding-hint muted">via {anchorHint}</p>
        )}
        {netHash && !network ? (
          <input
            value={netHash}
            onChange={e => setNetHash(e.target.value)}
            placeholder="network hash (64 hex)"
            autoComplete="off"
            autoFocus
            className="mono"
            style={{ fontSize: '0.72rem' }}
          />
        ) : (
          <input
            value={network}
            onChange={e => setNetwork(e.target.value)}
            placeholder="network name"
            autoComplete="off"
            autoFocus
          />
        )}
        {inviteString && (
          <p className="onboarding-hint muted mono" style={{ fontSize: '0.68rem', wordBreak: 'break-all' }}>
            {inviteString.slice(0, 48)}…
          </p>
        )}
        <button type="submit" className="primary" disabled={!network.trim() && netHash.length !== 64}>
          Join
        </button>
      </form>

      <div className="onboarding-section">
        <button
          className="toggle-link"
          onClick={() => setShowBackup(b => !b)}
        >
          {showBackup ? '▾' : '▸'} Identity backup
        </button>

        {showBackup && (
          <div className="backup-panel">
            <p className="onboarding-hint">
              Export your identity as an encrypted file. You can import it on
              any machine or in the TUI with <code>--import-identity</code>.
            </p>

            <form onSubmit={exportIdentity} className="backup-form">
              <input
                type="password"
                value={exportPass}
                onChange={e => setExportPass(e.target.value)}
                placeholder="passphrase for backup"
                autoComplete="new-password"
              />
              <button type="submit" disabled={!exportPass.trim()}>Export</button>
            </form>

            {exportedBackup && (
              <div className="export-result">
                <textarea
                  readOnly
                  value={exportedBackup}
                  rows={4}
                  className="mono"
                  onClick={e => (e.target as HTMLTextAreaElement).select()}
                />
                <button onClick={() => {
                  const a = document.createElement('a')
                  a.href = URL.createObjectURL(new Blob([exportedBackup], { type: 'application/json' }))
                  a.download = `waste-identity-${masterId?.slice(0, 8) ?? 'backup'}.json`
                  a.click()
                }}>Download file</button>
              </div>
            )}

            <details style={{ marginTop: '1rem' }}>
              <summary className="onboarding-hint" style={{ cursor: 'pointer' }}>Restore from backup</summary>
              <form onSubmit={importIdentity} className="backup-form" style={{ marginTop: '0.5rem' }}>
                <textarea
                  value={importJson}
                  onChange={e => setImportJson(e.target.value)}
                  placeholder='{"yaw":"yaw-key-backup-1", …}'
                  rows={3}
                  className="mono"
                />
                <input
                  type="password"
                  value={importPass}
                  onChange={e => setImportPass(e.target.value)}
                  placeholder="passphrase"
                  autoComplete="current-password"
                />
                <button type="submit" disabled={!importJson.trim() || !importPass.trim()}>
                  Verify & restore
                </button>
                {importStatus && <p className="onboarding-hint">{importStatus}</p>}
              </form>
            </details>
          </div>
        )}
      </div>
    </div>
  )
}
