'use client'
import { use, useState } from 'react'
import Link from 'next/link'
import { ArrowLeft, FlaskConical, GitCommit, ArrowLeftRight, BarChart2, Phone, Play, CheckCircle2, Key } from 'lucide-react'
import { DEMO_PROMPTS, DEMO_REQUESTS } from '@/lib/demo-data'
import { Topbar } from '@/components/layout/topbar'
import { cn } from '@/lib/utils'

type Tab = 'versions' | 'calls' | 'traffic' | 'ab' | 'diff' | 'playground'

const TABS: { id: Tab; label: string; icon: React.ReactNode }[] = [
  { id: 'versions',   label: 'Versions',   icon: <GitCommit className="h-3.5 w-3.5" /> },
  { id: 'diff',       label: 'Diff',       icon: <ArrowLeftRight className="h-3.5 w-3.5" /> },
  { id: 'traffic',    label: 'Traffic',    icon: <BarChart2 className="h-3.5 w-3.5" /> },
  { id: 'calls',      label: 'Calls',      icon: <Phone className="h-3.5 w-3.5" /> },
  { id: 'playground', label: 'Playground', icon: <Play className="h-3.5 w-3.5" /> },
  { id: 'ab',         label: 'A/B',        icon: <FlaskConical className="h-3.5 w-3.5" /> },
]

function fmtUsd(v: number): string {
  return v >= 1 ? `$${v.toFixed(2)}` : `$${v.toFixed(5)}`
}

function fmtMs(v: number): string {
  if (v === 0) return '—'
  if (v >= 1000) return `${(v / 1000).toFixed(2)}s`
  return `${Math.round(v)}ms`
}

// ── Versions Tab ──────────────────────────────────────────────────────────────

function VersionsTab({ prompt }: { prompt: (typeof DEMO_PROMPTS)[number] }) {
  return (
    <div className="p-[22px] space-y-6">
      {/* Current version card */}
      <div className="rounded-[8px] border border-border overflow-hidden">
        <div className="flex items-center gap-3 px-[18px] py-[12px] bg-bg-muted border-b border-border">
          <span className="font-mono text-[11px] font-semibold text-text">v{prompt.version}</span>
          <span className="font-mono text-[10px] uppercase tracking-[0.05em] px-[6px] py-[1px] rounded-[3px] bg-good/10 border border-good/20 text-good">
            current
          </span>
          <span className="font-mono text-[11px] text-text-faint ml-auto">
            {new Date(prompt.created_at).toLocaleDateString('en-US')} · by {prompt.created_by}
          </span>
        </div>

        {/* Content */}
        <div className="px-[18px] py-[14px] bg-bg">
          <div className="font-mono text-[10px] uppercase tracking-[0.05em] text-text-faint mb-2">
            Prompt content
          </div>
          <pre className="whitespace-pre-wrap font-mono text-[12.5px] text-text leading-relaxed bg-bg-elev rounded-[6px] px-[14px] py-[12px] border border-border overflow-x-auto">
            {prompt.content}
          </pre>
        </div>

        {/* Variables */}
        {prompt.variables && prompt.variables.length > 0 && (
          <div className="px-[18px] py-[14px] border-t border-border">
            <div className="font-mono text-[10px] uppercase tracking-[0.05em] text-text-faint mb-3">
              Variables · {prompt.variables.length}
            </div>
            <div className="space-y-2">
              {prompt.variables.map((v) => (
                <div key={v.name} className="flex items-start gap-3">
                  <code className="font-mono text-[12px] text-accent bg-accent-bg border border-accent-border px-[8px] py-[2px] rounded-[4px] shrink-0">
                    {`{{${v.name}}}`}
                  </code>
                  <div>
                    <span className="text-[12px] text-text-muted">{v.description}</span>
                    {v.required && (
                      <span className="ml-2 font-mono text-[10px] text-bad">required</span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Metadata */}
        {prompt.metadata && Object.keys(prompt.metadata).length > 0 && (
          <div className="px-[18px] py-[14px] border-t border-border">
            <div className="font-mono text-[10px] uppercase tracking-[0.05em] text-text-faint mb-3">
              Metadata
            </div>
            <div className="flex flex-wrap gap-x-6 gap-y-1">
              {Object.entries(prompt.metadata).map(([k, val]) => (
                <div key={k} className="flex items-center gap-2">
                  <span className="font-mono text-[11px] text-text-faint">{k}</span>
                  <span className="font-mono text-[11px] text-text">{String(val)}</span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Version history */}
      <div>
        <div className="font-mono text-[10px] uppercase tracking-[0.05em] text-text-faint mb-3">
          Version history · {prompt.versionCount ?? prompt.version} versions
        </div>
        <div className="rounded-[6px] border border-border overflow-hidden">
          {Array.from({ length: prompt.versionCount ?? prompt.version }, (_, i) => {
            const v = (prompt.versionCount ?? prompt.version) - i
            const isCurrent = v === prompt.version
            return (
              <div
                key={v}
                className={cn(
                  'flex items-center gap-3 px-[14px] py-[10px] border-b border-border last:border-0',
                  isCurrent && 'bg-bg-muted',
                )}
              >
                <span className="font-mono text-[12px] text-text-muted w-8">v{v}</span>
                {isCurrent && (
                  <span className="font-mono text-[9px] uppercase tracking-[0.05em] px-[5px] py-[1px] rounded-[3px] bg-good/10 border border-good/20 text-good">
                    current
                  </span>
                )}
                <span className="font-mono text-[11px] text-text-faint ml-auto">
                  {v === prompt.version
                    ? new Date(prompt.created_at).toLocaleDateString('en-US')
                    : new Date(
                        new Date(prompt.created_at).getTime() - (prompt.version - v) * 86400000 * 3,
                      ).toLocaleDateString('en-US')}
                </span>
                <span className="font-mono text-[11px] text-text-faint">{prompt.created_by}</span>
              </div>
            )
          })}
        </div>
      </div>
    </div>
  )
}

// ── Calls Tab ─────────────────────────────────────────────────────────────────

function CallsTab() {
  const requests = DEMO_REQUESTS.slice(0, 8)
  return (
    <div className="p-[22px]">
      <div className="font-mono text-[10px] uppercase tracking-[0.05em] text-text-faint mb-3">
        Recent calls linked to this prompt
      </div>
      <div className="rounded-[6px] border border-border overflow-hidden">
        {/* Header */}
        <div
          className="grid font-mono text-[10px] text-text-faint uppercase tracking-[0.05em] px-[14px] py-[8px] bg-bg-muted border-b border-border"
          style={{ gridTemplateColumns: '1fr 100px 80px 80px 80px 100px' }}
        >
          <span>Model</span>
          <span>Status</span>
          <span>Tokens</span>
          <span>Cost</span>
          <span>Latency</span>
          <span className="text-right">Time</span>
        </div>
        {requests.map((r) => (
          <div
            key={r.id}
            className={cn(
              'grid items-center px-[14px] py-[9px] border-b border-border last:border-0 font-mono text-[12px]',
            )}
            style={{ gridTemplateColumns: '1fr 100px 80px 80px 80px 100px' }}
          >
            <span className="text-text truncate">
              {r.provider} / {r.model}
            </span>
            <span>
              <span
                className={cn(
                  'px-[6px] py-[1px] rounded-[3px] text-[10px] uppercase tracking-[0.04em]',
                  r.status_code === 200
                    ? 'bg-good/10 text-good'
                    : 'bg-bad/10 text-bad',
                )}
              >
                {r.status_code}
              </span>
            </span>
            <span className="text-text-muted">{r.total_tokens.toLocaleString('en-US')}</span>
            <span className="text-text-muted">
              {r.cost_usd != null ? `$${r.cost_usd.toFixed(5)}` : '—'}
            </span>
            <span className="text-text-muted">{r.latency_ms}ms</span>
            <span className="text-text-faint text-right text-[11px]">
              {new Date(r.created_at).toLocaleTimeString('en-US')}
            </span>
          </div>
        ))}
      </div>
    </div>
  )
}

// ── Traffic Tab ───────────────────────────────────────────────────────────────

function TrafficTab({ prompt }: { prompt: (typeof DEMO_PROMPTS)[number] }) {
  const stats = prompt.stats
  if (!stats) return <div className="p-[22px] text-text-muted text-[13px]">No traffic data.</div>

  const statItems = [
    { label: 'Total calls',   value: stats.calls.toLocaleString('en-US') },
    { label: 'Total spend',   value: fmtUsd(stats.totalCostUsd) },
    { label: 'Avg cost/call', value: stats.avgCostUsd != null ? fmtUsd(stats.avgCostUsd) : '—' },
    { label: 'Avg latency',   value: stats.avgLatencyMs != null ? fmtMs(stats.avgLatencyMs) : '—' },
    { label: 'Error rate',    value: stats.errorRate != null ? `${(stats.errorRate * 100).toFixed(1)}%` : '—' },
  ]

  return (
    <div className="p-[22px]">
      <div className="font-mono text-[10px] uppercase tracking-[0.05em] text-text-faint mb-4">
        Traffic summary
      </div>
      <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
        {statItems.map((s) => (
          <div key={s.label} className="rounded-[6px] border border-border px-[14px] py-[12px] bg-bg-elev">
            <div className="font-mono text-[10px] text-text-faint uppercase tracking-[0.05em] mb-1">
              {s.label}
            </div>
            <div className="font-mono text-[18px] font-medium text-text">{s.value}</div>
          </div>
        ))}
      </div>

      <div className="mt-6 rounded-[6px] border border-dashed border-border py-10 text-center text-text-muted">
        <p className="text-[13px]">Time-series chart available in full account</p>
        <p className="font-mono text-[11px] text-text-faint mt-1">Sign up to see hourly call volume</p>
      </div>
    </div>
  )
}

// ── A/B Tab ───────────────────────────────────────────────────────────────────

function AbTab({ prompt }: { prompt: (typeof DEMO_PROMPTS)[number] }) {
  const exp = prompt.activeExperiment

  if (!exp) {
    return (
      <div className="p-[22px]">
        <div className="rounded-[6px] border border-dashed border-border py-12 text-center">
          <FlaskConical className="h-6 w-6 text-text-faint mx-auto mb-3" />
          <p className="text-[13px] text-text-muted">No A/B experiment running</p>
          <p className="font-mono text-[11px] text-text-faint mt-1">
            Sign up to create an A/B experiment for this prompt
          </p>
          <button
            type="button"
            onClick={() => alert('Sign up to create A/B experiments')}
            className="mt-4 font-mono text-[11.5px] px-4 py-[6px] rounded-[5px] bg-text text-bg font-medium hover:opacity-90 transition-opacity"
          >
            + New A/B test
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="p-[22px] space-y-4">
      <div className="flex items-center gap-3">
        <span className="inline-flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.05em] px-[8px] py-[3px] rounded-[4px] bg-accent-bg border border-accent-border text-accent">
          <FlaskConical className="h-3 w-3" />
          Experiment running
        </span>
        <span className="font-mono text-[11px] text-text-faint">ID: {exp.id}</span>
      </div>

      <div className="rounded-[6px] border border-border overflow-hidden">
        <div className="grid grid-cols-2 divide-x divide-border">
          {/* Control */}
          <div className="px-[18px] py-[14px]">
            <div className="font-mono text-[10px] uppercase tracking-[0.05em] text-text-faint mb-2">
              Control · v{prompt.version - 1}
            </div>
            <div className="text-[24px] font-medium text-text">
              {100 - exp.trafficSplit}%
            </div>
            <div className="font-mono text-[11px] text-text-faint mt-0.5">traffic</div>
          </div>
          {/* Variant */}
          <div className="px-[18px] py-[14px]">
            <div className="font-mono text-[10px] uppercase tracking-[0.05em] text-accent mb-2">
              Variant · v{prompt.version} (current)
            </div>
            <div className="text-[24px] font-medium text-accent">{exp.trafficSplit}%</div>
            <div className="font-mono text-[11px] text-text-faint mt-0.5">traffic</div>
          </div>
        </div>
        <div className="px-[18px] py-[10px] bg-bg-muted border-t border-border">
          <div className="flex gap-0 rounded-[4px] overflow-hidden border border-border h-3">
            <div
              className="bg-border-strong"
              style={{ width: `${100 - exp.trafficSplit}%` }}
            />
            <div className="bg-accent flex-1" />
          </div>
        </div>
      </div>

      <div className="rounded-[6px] border border-dashed border-border py-8 text-center text-text-muted">
        <p className="text-[13px]">Live experiment results available in full account</p>
        <p className="font-mono text-[11px] text-text-faint mt-1">
          Sign up to see quality scores, latency, and cost per variant
        </p>
      </div>
    </div>
  )
}

// ── Diff Tab ──────────────────────────────────────────────────────────────────

function DiffTab({ prompt }: { prompt: (typeof DEMO_PROMPTS)[number] }) {
  if ((prompt.versionCount ?? prompt.version) < 2) {
    return (
      <div className="p-[22px]">
        <div className="rounded-[6px] border border-dashed border-border py-12 text-center">
          <p className="text-[13px] text-text-muted">No version history to compare</p>
          <p className="font-mono text-[11px] text-text-faint mt-1">
            At least 2 versions are needed to show a diff
          </p>
        </div>
      </div>
    )
  }

  // Simulate a simple diff between "previous" and "current"
  const prevLines = [
    `You are a helpful assistant for {{company_name}}.`,
    `Your goal is to resolve customer issues.`,
    ``,
    `Customer message: {{customer_message}}`,
  ]
  const currLines = prompt.content.split('\n').slice(0, 6)

  return (
    <div className="p-[22px] space-y-4">
      <div className="flex items-center gap-3">
        <span className="font-mono text-[11px] text-text-muted">
          v{prompt.version - 1} → v{prompt.version}
        </span>
        <span className="font-mono text-[10px] text-text-faint">Latest diff</span>
      </div>

      <div className="rounded-[6px] border border-border overflow-hidden font-mono text-[12px]">
        {/* removed lines */}
        {prevLines.map((line, i) => (
          <div key={`r-${i}`} className="flex px-[14px] py-[3px] bg-bad/5 border-b border-bad/10">
            <span className="w-6 text-bad/60 select-none shrink-0">-</span>
            <span className="text-bad/80">{line || ' '}</span>
          </div>
        ))}
        {/* added lines */}
        {currLines.slice(0, 6).map((line, i) => (
          <div key={`a-${i}`} className="flex px-[14px] py-[3px] bg-good/5 border-b border-good/10 last:border-0">
            <span className="w-6 text-good/60 select-none shrink-0">+</span>
            <span className="text-good/80">{line || ' '}</span>
          </div>
        ))}
      </div>
    </div>
  )
}

// ── Playground Tab ────────────────────────────────────────────────────────────

const DEMO_PROVIDER_KEYS = [
  { id: 'pk-1', name: 'OpenAI prod',    provider: 'openai',    label: 'OpenAI' },
  { id: 'pk-2', name: 'Anthropic prod', provider: 'anthropic', label: 'Anthropic' },
  { id: 'pk-4', name: 'OpenAI staging', provider: 'openai',    label: 'OpenAI' },
]

const DEMO_MODELS_BY_PROVIDER: Record<string, string[]> = {
  openai: ['gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo'],
  anthropic: ['claude-sonnet-4-6', 'claude-opus-4-5', 'claude-3-5-haiku-20241022'],
  gemini: ['gemini-2.0-flash', 'gemini-1.5-pro'],
}

const VAR_RE = /\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g

function extractVars(content: string): string[] {
  const names = new Set<string>()
  for (const match of content.matchAll(VAR_RE)) {
    names.add(match[1]!)
  }
  return [...names]
}

function PlaygroundTab({ prompt }: { prompt: (typeof DEMO_PROMPTS)[number] }) {
  const [selectedKeyId, setSelectedKeyId] = useState(DEMO_PROVIDER_KEYS[0]?.id ?? '')
  const [model, setModel] = useState('claude-sonnet-4-6')
  const [temperature, setTemperature] = useState(0.7)
  const [maxTokens, setMaxTokens] = useState(1024)
  const [variables, setVariables] = useState<Record<string, string>>({})
  const [showResult, setShowResult] = useState(true)

  const selectedKey = DEMO_PROVIDER_KEYS.find((k) => k.id === selectedKeyId) ?? null
  const availableModels = selectedKey ? (DEMO_MODELS_BY_PROVIDER[selectedKey.provider] ?? []) : []
  const detectedVars = extractVars(prompt.content)

  // Static "demo" result — wired up to look like a real run completed.
  const demoResult = {
    model: model || 'claude-sonnet-4-6',
    promptTokens: 142,
    completionTokens: 187,
    totalTokens: 329,
    costUsd: 0.00428,
    latencyMs: 1248,
    responseText:
      "Thanks for reaching out! I understand you're experiencing an issue with your account.\n\nLet me take a look — based on what you described, I'd recommend the following steps:\n\n1. Verify your email address on file\n2. Reset your password from the login page\n3. Clear your browser cache and try again\n\nIf the problem persists, I can escalate to our technical team. Just let me know!",
  }

  return (
    <div className="flex h-full min-h-0">
      {/* Config panel */}
      <div className="w-[320px] shrink-0 border-r border-border overflow-y-auto p-[18px] space-y-5">
        <div className="space-y-1.5">
          <label className="font-mono text-[10px] uppercase tracking-[0.06em] text-text-faint">Version</label>
          <select
            value={`v${prompt.version}`}
            disabled
            className="w-full h-8 px-2 rounded-[4px] border border-border bg-bg font-mono text-[12px] text-text-muted opacity-80 cursor-not-allowed"
          >
            <option>v{prompt.version} (latest)</option>
          </select>
        </div>

        <div className="space-y-1.5">
          <label className="font-mono text-[10px] uppercase tracking-[0.06em] text-text-faint flex items-center gap-1.5">
            <Key className="h-3 w-3" /> Provider Key
          </label>
          <select
            value={selectedKeyId}
            onChange={(e) => setSelectedKeyId(e.target.value)}
            className="w-full h-8 px-2 rounded-[4px] border border-border bg-bg font-mono text-[12px] text-text focus:outline-none focus:border-border-strong"
          >
            {DEMO_PROVIDER_KEYS.map((k) => (
              <option key={k.id} value={k.id}>
                {k.name} · {k.label}
              </option>
            ))}
          </select>
        </div>

        {selectedKey && (
          <div className="space-y-1.5">
            <label className="font-mono text-[10px] uppercase tracking-[0.06em] text-text-faint">
              Model
              <span className="ml-2 px-[5px] py-[1px] rounded-[3px] bg-bg-elev border border-border text-text-muted normal-case tracking-normal">
                {selectedKey.label}
              </span>
            </label>
            <select
              value={model}
              onChange={(e) => setModel(e.target.value)}
              className="w-full h-8 px-2 rounded-[4px] border border-border bg-bg font-mono text-[12px] text-text focus:outline-none focus:border-border-strong"
            >
              {availableModels.map((m) => (
                <option key={m} value={m}>{m}</option>
              ))}
            </select>
          </div>
        )}

        <div className="space-y-1.5">
          <div className="flex items-center justify-between">
            <label className="font-mono text-[10px] uppercase tracking-[0.06em] text-text-faint">Temperature</label>
            <span className="font-mono text-[11px] text-text-muted">{temperature.toFixed(1)}</span>
          </div>
          <input
            type="range"
            min="0" max="2" step="0.1"
            value={temperature}
            onChange={(e) => setTemperature(parseFloat(e.target.value))}
            className="w-full accent-text"
          />
          <div className="flex justify-between font-mono text-[10px] text-text-faint">
            <span>0 precise</span>
            <span>2 creative</span>
          </div>
        </div>

        <div className="space-y-1.5">
          <div className="flex items-center justify-between">
            <label className="font-mono text-[10px] uppercase tracking-[0.06em] text-text-faint">Max tokens</label>
            <span className="font-mono text-[11px] text-text-muted">{maxTokens}</span>
          </div>
          <input
            type="number"
            min="1" max="8192"
            value={maxTokens}
            onChange={(e) =>
              setMaxTokens(Math.min(8192, Math.max(1, parseInt(e.target.value, 10) || 1)))
            }
            className="w-full h-8 px-2 rounded-[4px] border border-border bg-bg font-mono text-[12px] text-text focus:outline-none focus:border-border-strong"
          />
        </div>

        {detectedVars.length > 0 && (
          <div className="space-y-2.5">
            <label className="font-mono text-[10px] uppercase tracking-[0.06em] text-text-faint">Variables</label>
            {detectedVars.map((varName) => (
              <div key={varName} className="space-y-1">
                <label className="font-mono text-[11px] text-text-muted">{`{{${varName}}}`}</label>
                <input
                  type="text"
                  placeholder={`Value for ${varName}…`}
                  value={variables[varName] ?? ''}
                  onChange={(e) => setVariables((prev) => ({ ...prev, [varName]: e.target.value }))}
                  className="w-full h-8 px-2 rounded-[4px] border border-border bg-bg font-mono text-[12px] text-text placeholder:text-text-faint focus:outline-none focus:border-border-strong"
                />
              </div>
            ))}
          </div>
        )}

        <button
          type="button"
          onClick={() => setShowResult(true)}
          className="w-full flex items-center justify-center gap-2 h-9 rounded-[5px] bg-text text-bg font-mono text-[12px] font-medium hover:opacity-90 transition-opacity"
        >
          <Play className="h-3.5 w-3.5" />
          Run (demo)
        </button>

        <p className="font-mono text-[10.5px] text-text-faint text-center leading-relaxed">
          Playground is fully interactive in the live app.{' '}
          <Link href="/signup" className="text-accent hover:opacity-80">Sign up free</Link>{' '}
          to run against your own keys.
        </p>
      </div>

      {/* Preview + Result */}
      <div className="flex-1 min-w-0 overflow-y-auto flex flex-col">
        <div className="p-[18px] border-b border-border space-y-2 shrink-0">
          <p className="font-mono text-[10px] uppercase tracking-[0.06em] text-text-faint">Prompt preview</p>
          <div className="bg-bg-muted rounded-[6px] border border-border p-4 max-h-52 overflow-y-auto">
            <pre className="font-mono text-[12px] text-text-muted whitespace-pre-wrap leading-relaxed">
              {prompt.content}
            </pre>
          </div>
        </div>

        <div className="p-[18px] space-y-4 flex-1">
          {showResult && (
            <>
              <div className="grid grid-cols-4 gap-3">
                {[
                  { label: 'Model', value: demoResult.model },
                  { label: 'Tokens', value: demoResult.totalTokens.toLocaleString('en-US') },
                  { label: 'Cost', value: `$${demoResult.costUsd.toFixed(5)}` },
                  { label: 'Latency', value: `${(demoResult.latencyMs / 1000).toFixed(2)}s` },
                ].map((s) => (
                  <div key={s.label} className="bg-bg-elev rounded-[5px] border border-border px-3 py-2.5">
                    <p className="font-mono text-[9.5px] uppercase tracking-[0.06em] text-text-faint mb-1">
                      {s.label}
                    </p>
                    <p className="font-mono text-[12px] text-text font-medium truncate" title={s.value}>
                      {s.value}
                    </p>
                  </div>
                ))}
              </div>

              <div className="flex items-center flex-wrap gap-x-4 gap-y-1 font-mono text-[11px] text-text-faint">
                <span><span className="text-text-muted">{demoResult.promptTokens}</span> prompt</span>
                <span>+</span>
                <span><span className="text-text-muted">{demoResult.completionTokens}</span> completion</span>
                <span>=</span>
                <span><span className="text-text-muted">{demoResult.totalTokens}</span> total</span>
              </div>

              <div className="space-y-1.5">
                <div className="flex items-center gap-2">
                  <p className="font-mono text-[10px] uppercase tracking-[0.06em] text-text-faint">Response</p>
                  <CheckCircle2 className="h-3 w-3 text-good" />
                  <span className="font-mono text-[9px] uppercase tracking-[0.05em] px-1.5 py-0.5 rounded-[3px] bg-accent/10 border border-accent/20 text-accent ml-auto">
                    demo response
                  </span>
                </div>
                <div className="bg-bg-muted rounded-[6px] border border-border p-4">
                  <pre className="font-mono text-[12.5px] text-text whitespace-pre-wrap leading-relaxed">
                    {demoResult.responseText}
                  </pre>
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  )
}

// ── Main page ─────────────────────────────────────────────────────────────────

interface Props {
  params: Promise<{ name: string }>
}

export default function DemoPromptDetailPage({ params }: Props) {
  const { name: rawName } = use(params)
  const name = decodeURIComponent(rawName)
  const [tab, setTab] = useState<Tab>('versions')

  const prompt = DEMO_PROMPTS.find((p) => p.name === name)

  if (!prompt) {
    return (
      <div className="-mx-4 -my-4 md:-mx-8 md:-my-7 flex flex-col h-screen overflow-hidden bg-bg">
        <Topbar
          crumbs={[
            { label: 'Prompts', href: '/demo/prompts' },
            { label: name },
          ]}
        />
        <div className="flex flex-col items-center justify-center flex-1 gap-3 text-text-muted">
          <p className="text-[13px]">Prompt not found: {name}</p>
          <Link
            href="/demo/prompts"
            className="font-mono text-[11.5px] px-3 py-[5px] rounded-[4px] border border-border hover:text-text transition-colors"
          >
            ← Back to prompts
          </Link>
        </div>
      </div>
    )
  }

  const hasExperiment = Boolean(prompt.activeExperiment)

  return (
    <div className="-mx-4 -my-4 md:-mx-8 md:-my-7 flex flex-col h-screen overflow-hidden bg-bg">
      <Topbar
        crumbs={[
          { label: 'Prompts', href: '/demo/prompts' },
          { label: prompt.name },
        ]}
        right={
          <div className="flex items-center gap-2">
            <Link
              href="/demo/prompts"
              className="font-mono text-[11px] text-text-muted hover:text-text flex items-center gap-1 transition-colors"
            >
              <ArrowLeft className="h-3.5 w-3.5" />
              Back
            </Link>
          </div>
        }
      />

      {/* Header row */}
      <div className="flex items-center gap-3 px-[22px] py-[14px] border-b border-border shrink-0">
        <div className="flex-1 min-w-0">
          <h1 className="font-mono text-[15px] font-semibold text-text truncate">{prompt.name}</h1>
          <p className="font-mono text-[11px] text-text-faint mt-0.5">
            {prompt.versionCount ?? prompt.version} version
            {(prompt.versionCount ?? prompt.version) !== 1 ? 's' : ''}
          </p>
        </div>
        {hasExperiment && (
          <span className="inline-flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.05em] px-[8px] py-[3px] rounded-[4px] bg-accent-bg border border-accent-border text-accent">
            <FlaskConical className="h-3 w-3" />
            A/B running
          </span>
        )}
        <button
          type="button"
          onClick={() => setTab('ab')}
          className="font-mono text-[11px] text-text px-[10px] py-[5px] border border-border-strong rounded-[5px] bg-bg-elev hover:bg-bg-muted flex items-center gap-1.5 transition-colors"
        >
          <FlaskConical className="h-3.5 w-3.5" />
          {hasExperiment ? 'Manage A/B' : 'New A/B test'}
        </button>
      </div>

      {/* Tab bar */}
      <div className="flex items-center gap-0 px-[22px] border-b border-border shrink-0 bg-bg-muted overflow-x-auto">
        {TABS.map((t) => (
          <button
            key={t.id}
            type="button"
            onClick={() => setTab(t.id)}
            className={cn(
              'flex items-center gap-1.5 px-[14px] py-[10px] font-mono text-[11.5px] tracking-[0.02em] border-b-2 transition-colors',
              tab === t.id
                ? 'border-text text-text'
                : 'border-transparent text-text-faint hover:text-text-muted',
            )}
          >
            {t.icon}
            {t.label}
            {t.id === 'ab' && hasExperiment && (
              <span className="w-1.5 h-1.5 rounded-full bg-accent block" />
            )}
          </button>
        ))}
      </div>

      {/* Tab content */}
      <div className="flex-1 overflow-auto">
        {tab === 'versions'   && <VersionsTab prompt={prompt} />}
        {tab === 'calls'      && <CallsTab />}
        {tab === 'traffic'    && <TrafficTab prompt={prompt} />}
        {tab === 'ab'         && <AbTab prompt={prompt} />}
        {tab === 'diff'       && <DiffTab prompt={prompt} />}
        {tab === 'playground' && <PlaygroundTab prompt={prompt} />}
      </div>
    </div>
  )
}
