'use client'

import { useState, useEffect } from 'react'
import { useRouter, useParams } from 'next/navigation'
import Link from 'next/link'
import {
  ArrowLeft,
  Sparkles,
  Globe,
  User,
  Calendar,
  Code2,
  FileText,
  Copy,
  Check,
  Loader2,
} from 'lucide-react'

// ── Constants ──

const TYPE_OPTIONS = [
  { value: 'PETICAO_INICIAL', label: 'Petição Inicial' },
  { value: 'CONTESTACAO', label: 'Contestação' },
  { value: 'APELACAO', label: 'Apelação' },
  { value: 'RECURSO', label: 'Recurso' },
  { value: 'CONTRATO', label: 'Contrato' },
  { value: 'PARECER', label: 'Parecer' },
  { value: 'IMPUGNACAO', label: 'Impugnação' },
  { value: 'HABEAS_CORPUS', label: 'Habeas Corpus' },
  { value: 'MANDADO_SEGURANCA', label: 'Mandado de Segurança' },
  { value: 'OUTROS', label: 'Outros' },
]

const AREA_OPTIONS = [
  { value: 'CIVIL', label: 'Civil' },
  { value: 'TRABALHISTA', label: 'Trabalhista' },
  { value: 'PENAL', label: 'Penal' },
  { value: 'TRIBUTARIO', label: 'Tributário' },
  { value: 'FAMILIA', label: 'Família' },
  { value: 'EMPRESARIAL', label: 'Empresarial' },
  { value: 'CONSUMIDOR', label: 'Consumidor' },
  { value: 'ADMINISTRATIVO', label: 'Administrativo' },
]

const TYPE_COLORS: Record<string, string> = {
  PETICAO_INICIAL: 'bg-blue-500/15 text-blue-400 border-blue-500/30',
  CONTESTACAO: 'bg-red-500/15 text-red-400 border-red-500/30',
  APELACAO: 'bg-amber-500/15 text-amber-400 border-amber-500/30',
  RECURSO: 'bg-orange-500/15 text-orange-400 border-orange-500/30',
  CONTRATO: 'bg-emerald-500/15 text-emerald-400 border-emerald-500/30',
  PARECER: 'bg-cyan-500/15 text-cyan-400 border-cyan-500/30',
  IMPUGNACAO: 'bg-rose-500/15 text-rose-400 border-rose-500/30',
  HABEAS_CORPUS: 'bg-teal-500/15 text-teal-400 border-teal-500/30',
  MANDADO_SEGURANCA: 'bg-indigo-500/15 text-indigo-400 border-indigo-500/30',
  OUTROS: 'bg-zinc-500/15 text-zinc-400 border-zinc-500/30',
}

const AREA_COLORS: Record<string, string> = {
  CIVIL: 'bg-sky-500/15 text-sky-400 border-sky-500/30',
  TRABALHISTA: 'bg-yellow-500/15 text-yellow-400 border-yellow-500/30',
  PENAL: 'bg-red-500/15 text-red-400 border-red-500/30',
  TRIBUTARIO: 'bg-green-500/15 text-green-400 border-green-500/30',
  FAMILIA: 'bg-pink-500/15 text-pink-400 border-pink-500/30',
  EMPRESARIAL: 'bg-teal-500/15 text-teal-400 border-teal-500/30',
  CONSUMIDOR: 'bg-orange-500/15 text-orange-400 border-orange-500/30',
  ADMINISTRATIVO: 'bg-teal-500/15 text-teal-400 border-teal-500/30',
}

function getTypeLabel(value: string) {
  return TYPE_OPTIONS.find((t) => t.value === value)?.label ?? value
}

function getAreaLabel(value: string) {
  return AREA_OPTIONS.find((a) => a.value === value)?.label ?? value
}

// ── Types ──

interface Template {
  id: string
  name: string
  description: string
  type: string
  area: string
  prompt: string
  isPublic: boolean
  userId: string | null
  createdAt: string
}

// ── Page ──

export default function TemplateDetailPage() {
  const router = useRouter()
  const params = useParams()
  const id = params.id as string

  const [template, setTemplate] = useState<Template | null>(null)
  const [loading, setLoading] = useState(true)
  const [notFound, setNotFound] = useState(false)
  const [copied, setCopied] = useState(false)

  useEffect(() => {
    async function fetchTemplate() {
      try {
        const res = await fetch('/api/templates')
        if (res.ok) {
          const data = await res.json()
          const found = data.templates.find((t: Template) => t.id === id)
          if (found) {
            setTemplate(found)
          } else {
            setNotFound(true)
          }
        } else {
          setNotFound(true)
        }
      } catch {
        setNotFound(true)
      } finally {
        setLoading(false)
      }
    }
    fetchTemplate()
  }, [id])

  const handleUse = () => {
    if (!template) return
    const qp = new URLSearchParams({
      templateId: template.id,
      type: template.type,
      area: template.area,
      templateName: template.name,
    })
    router.push(`/dashboard/nova-peca?${qp.toString()}`)
  }

  const handleCopyPrompt = async () => {
    if (!template) return
    await navigator.clipboard.writeText(template.prompt)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-32">
        <Loader2 className="h-8 w-8 animate-spin text-teal-500" />
      </div>
    )
  }

  if (notFound || !template) {
    return (
      <div className="flex flex-col items-center justify-center py-32">
        <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-red-600/10">
          <FileText className="h-8 w-8 text-red-500/60" />
        </div>
        <h2 className="mt-4 text-lg font-semibold text-white">Modelo não encontrado</h2>
        <p className="mt-1 text-sm text-zinc-500">Este modelo não existe ou você não tem acesso.</p>
        <Link
          href="/dashboard/modelos"
          className="mt-4 flex items-center gap-2 rounded-xl bg-white/5 px-5 py-2.5 text-sm font-medium text-zinc-300 transition-colors hover:bg-white/10"
        >
          <ArrowLeft className="h-4 w-4" />
          Voltar aos Modelos
        </Link>
      </div>
    )
  }

  const variables = template.prompt.match(/\{\{(\w+)\}\}/g)?.map((v) => v.slice(2, -2)) ?? []
  const createdDate = new Date(template.createdAt).toLocaleDateString('pt-BR', {
    day: '2-digit',
    month: 'long',
    year: 'numeric',
  })

  // Highlight {{variables}} in the prompt
  const highlightedPrompt = template.prompt.split(/(\{\{\w+\}\})/).map((part, i) => {
    if (/^\{\{\w+\}\}$/.test(part)) {
      return (
        <span key={i} className="rounded bg-teal-600/20 px-1 text-teal-400">
          {part}
        </span>
      )
    }
    return part
  })

  return (
    <div className="space-y-6">
      {/* Back */}
      <Link
        href="/dashboard/modelos"
        className="inline-flex items-center gap-2 text-sm text-zinc-400 transition-colors hover:text-white"
      >
        <ArrowLeft className="h-4 w-4" />
        Voltar aos Modelos
      </Link>

      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <div className="mb-3 flex flex-wrap gap-2">
            <span
              className={`rounded-lg border px-2.5 py-1 text-xs font-bold uppercase tracking-wide ${
                TYPE_COLORS[template.type] ?? TYPE_COLORS.OUTROS
              }`}
            >
              {getTypeLabel(template.type)}
            </span>
            <span
              className={`rounded-lg border px-2.5 py-1 text-xs font-bold uppercase tracking-wide ${
                AREA_COLORS[template.area] ?? AREA_COLORS.CIVIL
              }`}
            >
              {getAreaLabel(template.area)}
            </span>
            {template.isPublic ? (
              <span className="flex items-center gap-1 rounded-lg border border-teal-500/30 bg-teal-500/15 px-2.5 py-1 text-xs font-bold text-teal-400">
                <Globe className="h-3 w-3" />
                Sistema
              </span>
            ) : (
              <span className="flex items-center gap-1 rounded-lg border border-emerald-500/30 bg-emerald-500/15 px-2.5 py-1 text-xs font-bold text-emerald-400">
                <User className="h-3 w-3" />
                Meu Modelo
              </span>
            )}
          </div>
          <h1 className="text-2xl font-bold text-white">{template.name}</h1>
          <p className="mt-2 text-sm leading-relaxed text-zinc-400">{template.description}</p>
          <div className="mt-3 flex items-center gap-1.5 text-xs text-zinc-500">
            <Calendar className="h-3.5 w-3.5" />
            Criado em {createdDate}
          </div>
        </div>

        <button
          onClick={handleUse}
          className="flex items-center gap-2 rounded-xl bg-teal-600 px-6 py-3 text-sm font-semibold text-white shadow-lg shadow-teal-600/20 transition-all hover:bg-teal-500 hover:shadow-teal-500/30"
        >
          <Sparkles className="h-4 w-4" />
          Usar este modelo
        </button>
      </div>

      {/* Variables */}
      {variables.length > 0 && (
        <div className="rounded-2xl border border-white/5 bg-white/[0.02] p-5">
          <h3 className="mb-3 flex items-center gap-2 text-sm font-semibold text-zinc-300">
            <Code2 className="h-4 w-4 text-teal-400" />
            Variáveis do Template ({variables.length})
          </h3>
          <div className="flex flex-wrap gap-2">
            {variables.map((v, i) => (
              <span
                key={i}
                className="rounded-lg border border-teal-500/20 bg-teal-600/10 px-3 py-1.5 font-mono text-sm text-teal-300"
              >
                {`{{${v}}}`}
              </span>
            ))}
          </div>
          <p className="mt-3 text-xs text-zinc-500">
            Estas variáveis serão preenchidas automaticamente ao usar o modelo para gerar uma peça.
          </p>
        </div>
      )}

      {/* Prompt Preview */}
      <div className="rounded-2xl border border-white/5 bg-white/[0.02] p-5">
        <div className="mb-3 flex items-center justify-between">
          <h3 className="flex items-center gap-2 text-sm font-semibold text-zinc-300">
            <FileText className="h-4 w-4 text-teal-400" />
            Prompt do Template
          </h3>
          <button
            onClick={handleCopyPrompt}
            className="flex items-center gap-1.5 rounded-lg border border-white/10 px-3 py-1.5 text-xs text-zinc-400 transition-colors hover:border-white/20 hover:text-white"
          >
            {copied ? (
              <>
                <Check className="h-3.5 w-3.5 text-emerald-400" />
                <span className="text-emerald-400">Copiado!</span>
              </>
            ) : (
              <>
                <Copy className="h-3.5 w-3.5" />
                Copiar
              </>
            )}
          </button>
        </div>
        <div className="rounded-xl bg-black/30 p-4 font-mono text-sm leading-relaxed text-zinc-300">
          <pre className="whitespace-pre-wrap break-words">{highlightedPrompt}</pre>
        </div>
      </div>
    </div>
  )
}
