import { useState } from 'react'
import { CheckCircle, Eye, EyeOff, Loader, Copy, Check, ArrowRight } from 'lucide-react'
import { invoke } from '@tauri-apps/api/core'

interface Props {
  initialKey?: string   // pre-filled from bibividi:// deep link
  onComplete: () => void
}

type Step = 1 | 2 | 3 | 4
type Provider = 'anthropic' | 'openai' | 'gemini'

const PROVIDER_LABELS: Record<Provider, string> = {
  anthropic: 'Anthropic',
  openai: 'OpenAI',
  gemini: 'Gemini',
}

const SDK_SNIPPETS: Record<Provider, string> = {
  anthropic: `import anthropic
from bvd.sdk import anthropic_http_client

client = anthropic.Anthropic(
    api_key="sk-ant-...",
    http_client=anthropic_http_client(),  # ← only change
)`,
  openai: `import openai
from bvd.sdk import openai_http_client

client = openai.OpenAI(
    api_key="sk-...",
    http_client=openai_http_client(),     # ← only change
)`,
  gemini: `import google.generativeai as genai
from bvd.sdk import gemini_http_client

genai.configure(
    api_key="AIza...",
    transport=gemini_http_client(),       # ← only change
)`,
}

function StepDots({ current }: { current: Step }) {
  return (
    <div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginBottom: 32 }}>
      {([1, 2, 3, 4] as Step[]).map(n => (
        <div
          key={n}
          style={{
            width: n === current ? 24 : 8,
            height: 8,
            borderRadius: 4,
            background: n === current
              ? 'var(--accent-light)'
              : n < current
                ? 'var(--green)'
                : 'var(--border)',
            transition: 'all 0.2s',
          }}
        />
      ))}
    </div>
  )
}

export default function Wizard({ initialKey = '', onComplete }: Props) {
  const [step, setStep] = useState<Step>(1)

  // Step 1
  const [licenseKey, setLicenseKey] = useState(initialKey)
  const [activating, setActivating] = useState(false)
  const [activateError, setActivateError] = useState('')

  // Step 2
  const [provider, setProvider] = useState<Provider>('anthropic')
  const [apiKey, setApiKey] = useState('')
  const [showApiKey, setShowApiKey] = useState(false)
  const [savingConfig, setSavingConfig] = useState(false)
  const [configError, setConfigError] = useState('')

  // Step 3
  const [running, setRunning] = useState(false)
  const [demoResult, setDemoResult] = useState<{
    tokens_before: number; tokens_after: number; saving_pct: number
  } | null>(null)
  const [demoError, setDemoError] = useState('')

  // Step 4
  const [copied, setCopied] = useState(false)

  // ── Step 1: activate license ────────────────────────────────────────────────

  async function handleActivate() {
    setActivateError('')
    setActivating(true)
    try {
      const res = await fetch('/bibividi/api/config/activate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ key: licenseKey }),
      })
      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        setActivateError(data.detail ?? `Error ${res.status}`)
        return
      }
      setStep(2)
    } catch {
      setActivateError('Could not reach proxy — is BIBIVIDI running?')
    } finally {
      setActivating(false)
    }
  }

  // ── Step 2: save API key + restart proxy ────────────────────────────────────

  async function handleSaveConfig() {
    setConfigError('')
    setSavingConfig(true)
    try {
      const res = await fetch('/bibividi/api/config', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ generator_api_key: apiKey, generator_provider: provider }),
      })
      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        setConfigError(data.detail ?? `Error ${res.status}`)
        return
      }
      // Restart proxy so it picks up the new API key
      await invoke('restart_proxy')
      setStep(3)
    } catch (err: unknown) {
      setConfigError(err instanceof Error ? err.message : 'Unexpected error')
    } finally {
      setSavingConfig(false)
    }
  }

  // ── Step 3: run demo ────────────────────────────────────────────────────────

  async function handleRunDemo() {
    setDemoError('')
    setRunning(true)
    try {
      const res = await fetch('/bibividi/api/demo', { method: 'POST' })
      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        setDemoError(data.detail ?? `Error ${res.status}`)
        return
      }
      setDemoResult(await res.json())
    } catch {
      setDemoError('Demo failed — check that the proxy is running.')
    } finally {
      setRunning(false)
    }
  }

  // ── Step 4: copy snippet ────────────────────────────────────────────────────

  function handleCopy() {
    navigator.clipboard.writeText(SDK_SNIPPETS[provider]).then(() => {
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    })
  }

  // ── Render ──────────────────────────────────────────────────────────────────

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: 'var(--bg)',
      padding: 24,
    }}>
      <div style={{
        width: '100%',
        maxWidth: 480,
        background: 'var(--bg2)',
        border: '1px solid var(--border)',
        borderRadius: 12,
        padding: '40px 36px',
      }}>
        {/* Logo */}
        <div style={{
          fontSize: 11,
          fontWeight: 700,
          letterSpacing: 3,
          color: 'var(--accent-light)',
          marginBottom: 8,
        }}>
          BIBIVIDI
        </div>
        <h1 style={{ fontSize: 20, color: 'var(--text-h)', marginBottom: 4 }}>
          {step === 1 && 'Activate your licence'}
          {step === 2 && 'Connect your AI provider'}
          {step === 3 && 'See it work'}
          {step === 4 && 'You\'re ready'}
        </h1>
        <p style={{ color: 'var(--muted)', fontSize: 13, marginBottom: 28 }}>
          {step === 1 && 'Enter the key from your welcome email.'}
          {step === 2 && 'BIBIVIDI needs your API key to generate skills automatically.'}
          {step === 3 && 'Run a live demo on a sample contract — no API call made.'}
          {step === 4 && 'Copy these 2 lines into your project and you\'re done.'}
        </p>

        <StepDots current={step} />

        {/* ── STEP 1 ── */}
        {step === 1 && (
          <div>
            <label style={{ display: 'block', fontSize: 12, color: 'var(--muted)', marginBottom: 6 }}>
              Licence key
            </label>
            <input
              type="text"
              placeholder="bvd-xxxxxxxx"
              value={licenseKey}
              onChange={e => { setLicenseKey(e.target.value); setActivateError('') }}
              onKeyDown={e => e.key === 'Enter' && handleActivate()}
              style={inputStyle}
              autoFocus
            />
            {activateError && <p style={errorStyle}>{activateError}</p>}
            <button
              onClick={handleActivate}
              disabled={!licenseKey.trim() || activating}
              style={primaryBtn}
            >
              {activating
                ? <><Loader size={14} className="spin" /> Activating…</>
                : <>Activate <ArrowRight size={14} /></>
              }
            </button>
          </div>
        )}

        {/* ── STEP 2 ── */}
        {step === 2 && (
          <div>
            <label style={{ display: 'block', fontSize: 12, color: 'var(--muted)', marginBottom: 8 }}>
              Provider
            </label>
            <div style={{ display: 'flex', gap: 8, marginBottom: 20 }}>
              {(['anthropic', 'openai', 'gemini'] as Provider[]).map(p => (
                <button
                  key={p}
                  onClick={() => setProvider(p)}
                  style={{
                    padding: '6px 14px',
                    borderRadius: 6,
                    border: '1px solid',
                    fontSize: 13,
                    borderColor: provider === p ? 'var(--accent-light)' : 'var(--border)',
                    color: provider === p ? 'var(--accent-light)' : 'var(--muted)',
                    background: provider === p ? 'var(--accent-dim)' : 'transparent',
                  }}
                >
                  {PROVIDER_LABELS[p]}
                </button>
              ))}
            </div>

            <label style={{ display: 'block', fontSize: 12, color: 'var(--muted)', marginBottom: 6 }}>
              API key
            </label>
            <div style={{ position: 'relative' }}>
              <input
                type={showApiKey ? 'text' : 'password'}
                placeholder={provider === 'anthropic' ? 'sk-ant-…' : provider === 'openai' ? 'sk-…' : 'AIza…'}
                value={apiKey}
                onChange={e => { setApiKey(e.target.value); setConfigError('') }}
                onKeyDown={e => e.key === 'Enter' && handleSaveConfig()}
                style={{ ...inputStyle, paddingRight: 40 }}
                autoFocus
              />
              <button
                onClick={() => setShowApiKey(!showApiKey)}
                style={{
                  position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)',
                  background: 'none', border: 'none', color: 'var(--muted)', padding: 4,
                }}
                tabIndex={-1}
              >
                {showApiKey ? <EyeOff size={14} /> : <Eye size={14} />}
              </button>
            </div>
            <p style={{ fontSize: 11, color: 'var(--muted)', marginTop: 6 }}>
              Used only for auto-generating skills. Stored locally in ~/.bibividi/.env.
            </p>
            {configError && <p style={errorStyle}>{configError}</p>}
            <button
              onClick={handleSaveConfig}
              disabled={!apiKey.trim() || savingConfig}
              style={primaryBtn}
            >
              {savingConfig
                ? <><Loader size={14} className="spin" /> Restarting proxy…</>
                : <>Continue <ArrowRight size={14} /></>
              }
            </button>
          </div>
        )}

        {/* ── STEP 3 ── */}
        {step === 3 && (
          <div>
            {!demoResult ? (
              <>
                <p style={{ fontSize: 13, color: 'var(--text)', marginBottom: 20, lineHeight: 1.7 }}>
                  We'll run the <code style={{ color: 'var(--accent-light)' }}>pdf-clause-extractor</code> skill
                  on a sample contract. The skill runs 100% locally — no API call is made.
                </p>
                {demoError && <p style={errorStyle}>{demoError}</p>}
                <button onClick={handleRunDemo} disabled={running} style={primaryBtn}>
                  {running
                    ? <><Loader size={14} className="spin" /> Running…</>
                    : <>▶ Run demo</>
                  }
                </button>
              </>
            ) : (
              <>
                <div style={{
                  display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 24,
                }}>
                  {[
                    { label: 'Before', value: `${demoResult.tokens_before.toLocaleString()} tokens`, muted: true },
                    { label: 'After', value: `${demoResult.tokens_after.toLocaleString()} tokens`, muted: true },
                    {
                      label: 'Saved',
                      value: `${demoResult.saving_pct}%`,
                      highlight: true,
                      span: true,
                    },
                  ].map(card => (
                    <div
                      key={card.label}
                      style={{
                        gridColumn: card.span ? '1 / -1' : undefined,
                        background: card.highlight ? 'var(--green-dim)' : 'var(--bg3)',
                        border: `1px solid ${card.highlight ? 'var(--green)' : 'var(--border)'}`,
                        borderRadius: 8,
                        padding: '14px 18px',
                        textAlign: 'center',
                      }}
                    >
                      <div style={{
                        fontSize: card.highlight ? 32 : 20,
                        fontWeight: 700,
                        color: card.highlight ? 'var(--green)' : 'var(--text-h)',
                      }}>
                        {card.value}
                      </div>
                      <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>
                        {card.label}
                      </div>
                    </div>
                  ))}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 20 }}>
                  <CheckCircle size={16} color="var(--green)" />
                  <span style={{ fontSize: 13, color: 'var(--text)' }}>
                    BIBIVIDI is working correctly.
                  </span>
                </div>
                <button onClick={() => setStep(4)} style={primaryBtn}>
                  Next <ArrowRight size={14} />
                </button>
              </>
            )}
          </div>
        )}

        {/* ── STEP 4 ── */}
        {step === 4 && (
          <div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
              {(['anthropic', 'openai', 'gemini'] as Provider[]).map(p => (
                <button
                  key={p}
                  onClick={() => setProvider(p)}
                  style={{
                    padding: '4px 12px',
                    borderRadius: 6,
                    border: '1px solid',
                    fontSize: 12,
                    borderColor: provider === p ? 'var(--accent-light)' : 'var(--border)',
                    color: provider === p ? 'var(--accent-light)' : 'var(--muted)',
                    background: provider === p ? 'var(--accent-dim)' : 'transparent',
                  }}
                >
                  {PROVIDER_LABELS[p]}
                </button>
              ))}
            </div>

            <div style={{ position: 'relative' }}>
              <pre style={{
                background: 'var(--bg)',
                border: '1px solid var(--border)',
                borderRadius: 8,
                padding: '14px 16px',
                fontSize: 12,
                color: 'var(--text)',
                overflow: 'auto',
                fontFamily: 'var(--mono)',
                lineHeight: 1.6,
              }}>
                {SDK_SNIPPETS[provider]}
              </pre>
              <button
                onClick={handleCopy}
                style={{
                  position: 'absolute', top: 10, right: 10,
                  background: 'var(--bg2)', border: '1px solid var(--border)',
                  borderRadius: 6, padding: '4px 8px',
                  display: 'flex', alignItems: 'center', gap: 4,
                  fontSize: 11, color: copied ? 'var(--green)' : 'var(--muted)',
                }}
              >
                {copied ? <><Check size={12} /> Copied</> : <><Copy size={12} /> Copy</>}
              </button>
            </div>

            <button onClick={onComplete} style={{ ...primaryBtn, marginTop: 24 }}>
              Open Dashboard <ArrowRight size={14} />
            </button>
          </div>
        )}
      </div>
    </div>
  )
}

// ── Shared styles ────────────────────────────────────────────────────────────

const inputStyle: React.CSSProperties = {
  width: '100%',
  background: 'var(--bg)',
  border: '1px solid var(--border)',
  borderRadius: 6,
  padding: '10px 12px',
  color: 'var(--text-h)',
  fontSize: 14,
  fontFamily: 'var(--mono)',
  outline: 'none',
}

const primaryBtn: React.CSSProperties = {
  marginTop: 20,
  width: '100%',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  gap: 8,
  padding: '11px 20px',
  background: 'var(--accent)',
  border: 'none',
  borderRadius: 8,
  color: '#fff',
  fontSize: 14,
  fontWeight: 600,
  cursor: 'pointer',
}

const errorStyle: React.CSSProperties = {
  marginTop: 8,
  fontSize: 12,
  color: 'var(--red)',
}
