'use client'

import { useEffect, useState, useCallback } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft, Lock, Save, GitFork, Eye, Code, FileText, BarChart3 } from 'lucide-react'
import TabEditor from './_components/TabEditors'

const TABLE_LABELS: Record<string, string> = {
  company: 'Company', team: 'Team', financials: 'Financials', market: 'Market',
  competitors: 'Competitors', features: 'Features', milestones: 'Milestones',
  metrics: 'Metrics', funding: 'Funding', products: 'Products',
  fm_scenarios: 'FM Scenarios', fm_assumptions: 'FM Assumptions',
}
const TABLE_NAMES = Object.keys(TABLE_LABELS)

interface Version {
  id: string; name: string; description: string | null
  status: 'draft' | 'committed'; parent_id: string | null; committed_at: string | null
}

type R = Record<string, unknown>

export default function VersionEditorPage() {
  const { id } = useParams<{ id: string }>()
  const router = useRouter()
  const [version, setVersion] = useState<Version | null>(null)
  const [allData, setAllData] = useState<Record<string, unknown[]>>({})
  const [activeTab, setActiveTab] = useState('company')
  const [loading, setLoading] = useState(true)
  const [dirty, setDirty] = useState(false)
  const [saving, setSaving] = useState(false)
  const [jsonMode, setJsonMode] = useState(false)
  const [jsonText, setJsonText] = useState('')
  const [toast, setToast] = useState<string | null>(null)

  function flashToast(msg: string) { setToast(msg); setTimeout(() => setToast(null), 3000) }

  const load = useCallback(async () => {
    setLoading(true)
    const res = await fetch(`/api/admin/versions/${id}`)
    if (res.ok) { const d = await res.json(); setVersion(d.version); setAllData(d.data) }
    setLoading(false)
  }, [id])

  useEffect(() => { if (id) load() }, [id, load])

  // Sync JSON text when switching tabs or toggling JSON mode
  useEffect(() => {
    if (jsonMode) setJsonText(JSON.stringify(allData[activeTab] || [], null, 2))
  }, [activeTab, jsonMode, allData])

  function updateData(newData: unknown[]) {
    setAllData(prev => ({ ...prev, [activeTab]: newData }))
    setDirty(true)
  }

  function updateRecord(index: number, key: string, value: unknown) {
    const arr = [...(allData[activeTab] as R[] || [])]
    arr[index] = { ...arr[index], [key]: value }
    updateData(arr)
  }

  function updateSingle(key: string, value: unknown) { updateRecord(0, key, value) }

  async function saveTable() {
    let data: unknown
    if (jsonMode) {
      try { data = JSON.parse(jsonText) } catch { flashToast('Invalid JSON'); return }
    } else {
      data = allData[activeTab]
    }

    setSaving(true)
    const res = await fetch(`/api/admin/versions/${id}/data/${activeTab}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ data }),
    })
    setSaving(false)
    if (res.ok) {
      setDirty(false)
      if (jsonMode) setAllData(prev => ({ ...prev, [activeTab]: Array.isArray(data) ? data : [data] }))
      flashToast('Saved')
    } else { const d = await res.json().catch(() => ({})); flashToast(d.error || 'Save failed') }
  }

  async function commitVersion() {
    if (!confirm('Commit this version? It becomes immutable.')) return
    const res = await fetch(`/api/admin/versions/${id}/commit`, { method: 'POST' })
    if (res.ok) { flashToast('Committed'); load() }
    else { const d = await res.json().catch(() => ({})); flashToast(d.error || 'Failed') }
  }

  async function forkVersion() {
    const name = prompt('Name for the new draft:')
    if (!name) return
    const res = await fetch(`/api/admin/versions/${id}/fork`, {
      method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }),
    })
    if (res.ok) { const d = await res.json(); router.push(`/pitch-admin/versions/${d.version.id}`) }
    else { const d = await res.json().catch(() => ({})); flashToast(d.error || 'Failed') }
  }

  if (loading) return <div className="flex items-center justify-center h-64"><div className="w-8 h-8 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" /></div>
  if (!version) return <div className="text-rose-400">Version not found</div>

  const isDraft = version.status === 'draft'
  const data = allData[activeTab] || []
  const single = (data as R[])[0] || {} as R

  return (
    <div className="space-y-6">
      <Link href="/pitch-admin/versions" className="inline-flex items-center gap-2 text-sm text-white/50 hover:text-white/80">
        <ArrowLeft className="w-4 h-4" /> Back to versions
      </Link>

      {/* Header */}
      <div className="flex items-start justify-between gap-4 flex-wrap">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <h1 className="text-2xl font-semibold text-white">{version.name}</h1>
            <span className={`text-[9px] px-2 py-0.5 rounded-full border uppercase font-semibold ${
              isDraft ? 'bg-amber-500/15 text-amber-300 border-amber-500/30' : 'bg-green-500/15 text-green-300 border-green-500/30'
            }`}>{version.status}</span>
          </div>
          {version.description && <p className="text-sm text-white/50">{version.description}</p>}
        </div>
        <div className="flex items-center gap-2">
          <Link
            href={`/pitch-preview/${id}`}
            target="_blank"
            className="bg-white/[0.06] hover:bg-white/[0.1] text-white text-sm px-4 py-2 rounded-lg flex items-center gap-2"
          >
            <Eye className="w-4 h-4" /> Preview
          </Link>
          <Link
            href={`/pitch-print/${id}`}
            target="_blank"
            className="bg-white/[0.06] hover:bg-white/[0.1] text-white text-sm px-4 py-2 rounded-lg flex items-center gap-2"
          >
            <FileText className="w-4 h-4" /> Export PDF
          </Link>
          <Link
            href={`/pitch-print/${id}?financial=true`}
            target="_blank"
            className="bg-indigo-500/15 hover:bg-indigo-500/25 text-indigo-300 text-sm px-4 py-2 rounded-lg flex items-center gap-2"
          >
            <BarChart3 className="w-4 h-4" /> Export PDF + Financial
          </Link>
          {isDraft && (
            <button onClick={commitVersion} className="bg-green-500/15 hover:bg-green-500/25 text-green-300 text-sm px-4 py-2 rounded-lg flex items-center gap-2">
              <Lock className="w-4 h-4" /> Commit
            </button>
          )}
          <button onClick={forkVersion} className="bg-indigo-500/15 hover:bg-indigo-500/25 text-indigo-300 text-sm px-4 py-2 rounded-lg flex items-center gap-2">
            <GitFork className="w-4 h-4" /> Fork
          </button>
          {version.parent_id && (
            <Link href={`/pitch-admin/versions/${id}/diff/${version.parent_id}`} className="bg-white/[0.06] hover:bg-white/[0.1] text-white text-sm px-4 py-2 rounded-lg">
              Diff
            </Link>
          )}
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 overflow-x-auto pb-1">
        {TABLE_NAMES.map(tab => (
          <button
            key={tab}
            onClick={() => { if (dirty && !confirm('Discard unsaved changes?')) return; setActiveTab(tab); setDirty(false); setJsonMode(false) }}
            className={`px-3 py-1.5 rounded-lg text-xs whitespace-nowrap transition-colors ${
              activeTab === tab
                ? 'bg-indigo-500/20 text-indigo-300 border border-indigo-500/30'
                : 'bg-white/[0.04] text-white/40 border border-transparent hover:text-white/60'
            }`}
          >
            {TABLE_LABELS[tab]}
          </button>
        ))}
      </div>

      {/* Editor */}
      <div className="bg-white/[0.04] border border-white/[0.06] rounded-2xl overflow-hidden">
        <div className="flex items-center justify-between px-4 py-3 border-b border-white/[0.06]">
          <div className="flex items-center gap-3">
            <span className="text-sm font-semibold text-white">{TABLE_LABELS[activeTab]}</span>
            {dirty && <span className="text-[9px] px-2 py-0.5 rounded bg-amber-500/20 text-amber-300">Unsaved</span>}
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setJsonMode(!jsonMode)}
              className={`text-[10px] px-2 py-1 rounded flex items-center gap-1 transition-colors ${
                jsonMode ? 'bg-indigo-500/20 text-indigo-300' : 'bg-white/[0.04] text-white/40 hover:text-white/60'
              }`}
            >
              <Code className="w-3 h-3" /> {jsonMode ? 'Form' : 'JSON'}
            </button>
            {isDraft && (
              <button
                onClick={saveTable}
                disabled={saving || !dirty}
                className="bg-indigo-500 hover:bg-indigo-600 text-white text-sm font-medium px-4 py-1.5 rounded-lg flex items-center gap-2 disabled:opacity-30"
              >
                <Save className="w-3.5 h-3.5" /> {saving ? 'Saving...' : 'Save'}
              </button>
            )}
          </div>
        </div>
        <TabEditor
          activeTab={activeTab}
          data={data}
          single={single}
          jsonMode={jsonMode}
          jsonText={jsonText}
          isDraft={isDraft}
          onJsonTextChange={setJsonText}
          onDirty={() => setDirty(true)}
          updateData={updateData}
          updateRecord={updateRecord}
          updateSingle={updateSingle}
        />
      </div>

      {!isDraft && <p className="text-xs text-white/30 text-center">Committed -- read-only. Fork to edit.</p>}

      {toast && (
        <div className="fixed bottom-6 right-6 bg-indigo-500/20 border border-indigo-500/40 text-indigo-200 text-sm px-4 py-2 rounded-lg backdrop-blur-sm z-50">
          {toast}
        </div>
      )}
    </div>
  )
}
