'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'

interface VersionOption {
  id: string
  name: string
  status: string
}

export default function NewVersionPage() {
  const router = useRouter()
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [parentId, setParentId] = useState<string>('')
  const [versions, setVersions] = useState<VersionOption[]>([])
  const [error, setError] = useState('')
  const [submitting, setSubmitting] = useState(false)

  useEffect(() => {
    fetch('/api/admin/versions')
      .then(r => r.json())
      .then(d => setVersions(d.versions || []))
  }, [])

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError('')
    setSubmitting(true)
    const res = await fetch('/api/admin/versions', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name,
        description: description || undefined,
        parent_id: parentId || undefined,
      }),
    })
    setSubmitting(false)
    if (res.ok) {
      const d = await res.json()
      router.push(`/pitch-admin/versions/${d.version.id}`)
    } else {
      const d = await res.json().catch(() => ({}))
      setError(d.error || 'Creation failed')
    }
  }

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

      <h1 className="text-2xl font-semibold text-white mb-2">Create Version</h1>
      <p className="text-sm text-white/50 mb-6">
        A new draft will be created with a full copy of all pitch data.
        Choose a parent to fork from, or leave empty to snapshot the current base tables.
      </p>

      <form onSubmit={handleSubmit} className="bg-white/[0.04] border border-white/[0.08] rounded-2xl p-6 space-y-4">
        <div>
          <label className="block text-xs font-medium text-white/60 uppercase tracking-wider mb-2">
            Name <span className="text-rose-400">*</span>
          </label>
          <input
            value={name}
            onChange={e => setName(e.target.value)}
            required
            placeholder="e.g. Conservative Q4, Series A Ready"
            className="w-full bg-black/30 border border-white/10 rounded-lg px-3 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
          />
        </div>

        <div>
          <label className="block text-xs font-medium text-white/60 uppercase tracking-wider mb-2">Description</label>
          <textarea
            value={description}
            onChange={e => setDescription(e.target.value)}
            rows={2}
            placeholder="Optional notes about this version"
            className="w-full bg-black/30 border border-white/10 rounded-lg px-3 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40 resize-none"
          />
        </div>

        <div>
          <label className="block text-xs font-medium text-white/60 uppercase tracking-wider mb-2">Fork from</label>
          <select
            value={parentId}
            onChange={e => setParentId(e.target.value)}
            className="w-full bg-black/30 border border-white/10 rounded-lg px-3 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
          >
            <option value="">Base tables (current pitch data)</option>
            {versions.map(v => (
              <option key={v.id} value={v.id}>{v.name} ({v.status})</option>
            ))}
          </select>
        </div>

        {error && (
          <div className="text-sm text-rose-300 bg-rose-500/10 border border-rose-500/20 rounded-lg px-3 py-2">{error}</div>
        )}

        <div className="flex justify-end gap-3 pt-2">
          <Link href="/pitch-admin/versions" className="text-sm text-white/60 hover:text-white px-4 py-2">Cancel</Link>
          <button
            type="submit"
            disabled={submitting}
            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-5 py-2.5 rounded-lg disabled:opacity-50 shadow-lg shadow-indigo-500/20"
          >
            {submitting ? 'Creating…' : 'Create draft'}
          </button>
        </div>
      </form>
    </div>
  )
}
