'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { GitBranch, Plus, Lock, Pencil, Trash2, GitFork, Users } from 'lucide-react'

interface Version {
  id: string
  name: string
  description: string | null
  parent_id: string | null
  status: 'draft' | 'committed'
  created_by_name: string | null
  created_by_email: string | null
  committed_at: string | null
  created_at: string
  assigned_count: number
}

export default function VersionsPage() {
  const [versions, setVersions] = useState<Version[]>([])
  const [loading, setLoading] = useState(true)
  const [busy, setBusy] = useState<string | null>(null)
  const [toast, setToast] = useState<string | null>(null)

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

  async function load() {
    setLoading(true)
    const res = await fetch('/api/admin/versions')
    if (res.ok) { const d = await res.json(); setVersions(d.versions) }
    setLoading(false)
  }

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

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

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

  async function deleteVersion(id: string, name: string) {
    if (!confirm(`Delete "${name}"? This cannot be undone.`)) return
    setBusy(id)
    const res = await fetch(`/api/admin/versions/${id}`, { method: 'DELETE' })
    setBusy(null)
    if (res.ok) { flashToast('Deleted'); load() }
    else { const d = await res.json().catch(() => ({})); flashToast(d.error || 'Failed') }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold text-white">Pitch Versions</h1>
          <p className="text-sm text-white/50 mt-1">
            {versions.length} version{versions.length !== 1 ? 's' : ''} — each is a complete snapshot of all pitch data
          </p>
        </div>
        <Link
          href="/pitch-admin/versions/new"
          className="bg-gradient-to-r from-indigo-500 to-purple-600 hover:from-indigo-600 hover:to-purple-700 text-white text-sm font-medium px-4 py-2 rounded-lg shadow-lg shadow-indigo-500/20 flex items-center gap-2"
        >
          <Plus className="w-4 h-4" /> New Version
        </Link>
      </div>

      {loading ? (
        <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>
      ) : versions.length === 0 ? (
        <div className="bg-white/[0.04] border border-white/[0.06] rounded-2xl p-12 text-center">
          <GitBranch className="w-12 h-12 text-white/20 mx-auto mb-4" />
          <p className="text-white/60 mb-4">No versions yet. Create your first version to snapshot the current pitch data.</p>
          <Link
            href="/pitch-admin/versions/new"
            className="bg-indigo-500 hover:bg-indigo-600 text-white text-sm font-medium px-4 py-2 rounded-lg inline-flex items-center gap-2"
          >
            <Plus className="w-4 h-4" /> Create First Version
          </Link>
        </div>
      ) : (
        <div className="space-y-3">
          {versions.map(v => {
            const parent = v.parent_id ? versions.find(p => p.id === v.parent_id) : null
            return (
              <div key={v.id} className="bg-white/[0.04] border border-white/[0.06] rounded-2xl p-5 hover:border-white/[0.12] transition-colors">
                <div className="flex items-start justify-between gap-4">
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2 mb-1 flex-wrap">
                      <Link href={`/pitch-admin/versions/${v.id}`} className="text-base font-semibold text-white hover:text-indigo-300">
                        {v.name}
                      </Link>
                      <span className={`text-[9px] px-2 py-0.5 rounded-full border uppercase font-semibold ${
                        v.status === 'committed'
                          ? 'bg-green-500/15 text-green-300 border-green-500/30'
                          : 'bg-amber-500/15 text-amber-300 border-amber-500/30'
                      }`}>
                        {v.status}
                      </span>
                      {v.assigned_count > 0 && (
                        <span className="text-[9px] px-2 py-0.5 rounded-full bg-indigo-500/15 text-indigo-300 border border-indigo-500/30 flex items-center gap-1">
                          <Users className="w-3 h-3" /> {v.assigned_count}
                        </span>
                      )}
                    </div>
                    {v.description && <p className="text-sm text-white/50 mb-1">{v.description}</p>}
                    <div className="flex items-center gap-3 text-xs text-white/40">
                      <span>by {v.created_by_name || v.created_by_email || 'system'}</span>
                      <span>{new Date(v.created_at).toLocaleDateString()}</span>
                      {parent && (
                        <span className="flex items-center gap-1">
                          <GitBranch className="w-3 h-3" /> from {parent.name}
                        </span>
                      )}
                      {v.committed_at && <span>committed {new Date(v.committed_at).toLocaleDateString()}</span>}
                    </div>
                  </div>

                  <div className="flex items-center gap-1 shrink-0">
                    <Link
                      href={`/pitch-admin/versions/${v.id}`}
                      className="w-8 h-8 rounded-lg flex items-center justify-center text-white/50 hover:bg-white/[0.06] hover:text-white"
                      title="Edit"
                    >
                      <Pencil className="w-4 h-4" />
                    </Link>
                    {v.status === 'draft' && (
                      <button
                        onClick={() => commitVersion(v.id)}
                        disabled={busy === v.id}
                        className="w-8 h-8 rounded-lg flex items-center justify-center text-white/50 hover:bg-green-500/15 hover:text-green-300 disabled:opacity-30"
                        title="Commit"
                      >
                        <Lock className="w-4 h-4" />
                      </button>
                    )}
                    <button
                      onClick={() => forkVersion(v.id)}
                      disabled={busy === v.id}
                      className="w-8 h-8 rounded-lg flex items-center justify-center text-white/50 hover:bg-indigo-500/15 hover:text-indigo-300 disabled:opacity-30"
                      title="Fork"
                    >
                      <GitFork className="w-4 h-4" />
                    </button>
                    <button
                      onClick={() => deleteVersion(v.id, v.name)}
                      disabled={busy === v.id}
                      className="w-8 h-8 rounded-lg flex items-center justify-center text-white/50 hover:bg-rose-500/15 hover:text-rose-300 disabled:opacity-30"
                      title="Delete"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>

                {/* Quick diff link if has parent */}
                {v.parent_id && (
                  <div className="mt-3 pt-3 border-t border-white/[0.04]">
                    <Link
                      href={`/pitch-admin/versions/${v.id}/diff/${v.parent_id}`}
                      className="text-xs text-indigo-400 hover:text-indigo-300"
                    >
                      Compare with parent →
                    </Link>
                  </div>
                )}
              </div>
            )
          })}
        </div>
      )}

      {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>
  )
}
