'use client'

import { useState } from 'react'
import { GHLRenderer } from '@/lib/GHLRenderer'
import type { UITree } from '@json-render/core'
import Link from 'next/link'

const EXAMPLE_PROMPTS = [
  "Show a dashboard with contacts table on top, campaign stats below, and a pipeline summary on the right",
  "Build an invoice preview for invoice INV-2026-0142 from Acme Corp to TechStart LLC, with 3 line items, totals, and action buttons",
  "Create a CRM overview: stats grid with 4 metrics (contacts, deals, revenue, conversion rate), then a split layout with recent contacts on the left and activity timeline on the right",
  "Show a pipeline board with 5 stages (New Lead, Qualified, Proposal, Negotiation, Closed Won) with 2-3 deals each, total values per stage",
  "Build a campaign performance dashboard for 'Q1 Product Launch' — show key metrics (sent, delivered, opens, clicks), delivery progress bar, and a breakdown table",
]

const SAMPLE_JSON = `{
  "root": "demo",
  "elements": {
    "demo": {
      "key": "demo",
      "type": "Card",
      "props": { "title": "Hello from json-render!" },
      "children": ["metric", "bar"]
    },
    "metric": {
      "key": "metric",
      "type": "MetricCard",
      "props": { "label": "Revenue", "value": "$125,000", "color": "green", "trend": "up", "trendValue": "+12.5%" }
    },
    "bar": {
      "key": "bar",
      "type": "ProgressBar",
      "props": { "label": "Goal Progress", "value": 125000, "max": 200000, "color": "purple" }
    }
  }
}`

export default function PlaygroundPage() {
  const [mode, setMode] = useState<'ai' | 'json'>('ai')
  const [prompt, setPrompt] = useState('')
  const [json, setJson] = useState(SAMPLE_JSON)
  const [tree, setTree] = useState<UITree | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)
  const [rawJson, setRawJson] = useState<string | null>(null)

  const generateFromAI = async () => {
    if (!prompt.trim()) return
    setLoading(true)
    setError(null)
    setTree(null)
    setRawJson(null)

    try {
      const res = await fetch('/api/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt: prompt.trim() }),
      })

      const data = await res.json()

      if (!res.ok) {
        throw new Error(data.error || `HTTP ${res.status}`)
      }

      setTree(data.tree)
      setRawJson(JSON.stringify(data.tree, null, 2))
    } catch (e) {
      setError(String(e))
    } finally {
      setLoading(false)
    }
  }

  const renderJSON = () => {
    try {
      const parsed = JSON.parse(json)
      if (!parsed.root || !parsed.elements) {
        throw new Error('JSON must have "root" and "elements" keys')
      }
      setTree(parsed)
      setRawJson(json)
      setError(null)
    } catch (e) {
      setError(String(e))
      setTree(null)
    }
  }

  return (
    <div className="min-h-screen bg-gray-100">
      {/* Nav */}
      <nav className="bg-white border-b border-gray-200 px-4 py-2 flex items-center gap-3">
        <Link href="/" className="text-indigo-600 hover:text-indigo-800 text-sm font-medium">← Back</Link>
        <span className="text-gray-400">|</span>
        <span className="text-sm text-gray-600 font-medium">GHL UI Playground</span>
        <div className="ml-auto flex gap-1 bg-gray-100 rounded-lg p-0.5">
          <button
            onClick={() => setMode('ai')}
            className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${
              mode === 'ai' ? 'bg-indigo-600 text-white' : 'text-gray-600 hover:text-gray-800'
            }`}
          >
            AI Compose
          </button>
          <button
            onClick={() => setMode('json')}
            className={`px-3 py-1 text-xs font-medium rounded-md transition-colors ${
              mode === 'json' ? 'bg-indigo-600 text-white' : 'text-gray-600 hover:text-gray-800'
            }`}
          >
            JSON Editor
          </button>
        </div>
      </nav>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 p-4 max-w-[1600px] mx-auto" style={{ minHeight: 'calc(100vh - 50px)' }}>
        {/* Left Panel — Input */}
        <div className="flex flex-col gap-3">
          {mode === 'ai' ? (
            <>
              <div className="flex items-center justify-between">
                <h2 className="text-sm font-semibold text-gray-700">Describe the UI you want</h2>
                <button
                  onClick={generateFromAI}
                  disabled={loading || !prompt.trim()}
                  className="px-4 py-1.5 bg-indigo-600 text-white text-sm rounded-md hover:bg-indigo-700 transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
                >
                  {loading ? (
                    <>
                      <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                      </svg>
                      Generating...
                    </>
                  ) : 'Generate UI →'}
                </button>
              </div>
              <textarea
                value={prompt}
                onChange={e => setPrompt(e.target.value)}
                onKeyDown={e => { if (e.key === 'Enter' && e.metaKey) generateFromAI() }}
                placeholder="e.g. Show a dashboard with contacts on the left, pipeline on the right, and campaign stats below..."
                className="flex-none h-32 p-4 text-sm bg-white rounded-xl border border-gray-200 outline-none resize-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              />
              {/* Example prompts */}
              <div className="flex flex-col gap-1.5">
                <span className="text-xs font-medium text-gray-500 uppercase tracking-wide">Try these:</span>
                {EXAMPLE_PROMPTS.map((ex, i) => (
                  <button
                    key={i}
                    onClick={() => setPrompt(ex)}
                    className="text-left text-xs text-indigo-600 hover:text-indigo-800 hover:bg-indigo-50 px-2 py-1.5 rounded-md transition-colors truncate"
                  >
                    {ex}
                  </button>
                ))}
              </div>
              {/* Show generated JSON */}
              {rawJson && (
                <div className="flex flex-col gap-1">
                  <span className="text-xs font-medium text-gray-500 uppercase tracking-wide">Generated JSON Tree:</span>
                  <pre className="flex-1 min-h-[200px] max-h-[400px] overflow-auto p-4 font-mono text-xs bg-gray-900 text-green-400 rounded-xl">
                    {rawJson}
                  </pre>
                </div>
              )}
            </>
          ) : (
            <>
              <div className="flex items-center justify-between">
                <h2 className="text-sm font-semibold text-gray-700">JSON Tree Input</h2>
                <button
                  onClick={renderJSON}
                  className="px-4 py-1.5 bg-indigo-600 text-white text-sm rounded-md hover:bg-indigo-700 transition-colors font-medium"
                >
                  Render →
                </button>
              </div>
              <textarea
                value={json}
                onChange={e => setJson(e.target.value)}
                className="flex-1 min-h-[500px] p-4 font-mono text-sm bg-gray-900 text-green-400 rounded-xl border-0 outline-none resize-none"
                spellCheck={false}
              />
            </>
          )}
        </div>

        {/* Right Panel — Preview */}
        <div className="flex flex-col">
          <h2 className="text-sm font-semibold text-gray-700 mb-2">Rendered Output</h2>
          <div className="flex-1 bg-white rounded-xl border border-gray-200 p-4 overflow-auto shadow-sm">
            {loading && (
              <div className="flex flex-col items-center justify-center h-full gap-3 text-gray-400">
                <svg className="animate-spin h-8 w-8 text-indigo-500" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                </svg>
                <span className="text-sm">Claude is composing your UI...</span>
              </div>
            )}
            {error && (
              <div className="p-4 bg-red-50 text-red-700 rounded-lg text-sm mb-3">
                <strong>Error:</strong> {error}
              </div>
            )}
            {tree && !loading ? (
              <GHLRenderer tree={tree} />
            ) : !loading && !error ? (
              <div className="flex items-center justify-center h-full text-gray-400 text-sm">
                {mode === 'ai' ? 'Type a prompt and click "Generate UI →"' : 'Click "Render →" to see the output'}
              </div>
            ) : null}
          </div>
        </div>
      </div>
    </div>
  )
}
