'use client'

import { useState, useEffect, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import {
  BookTemplate,
  Plus,
  Search,
  Filter,
  X,
  Sparkles,
  Globe,
  User,
  ArrowRight,
  Loader2,
  FileText,
  Code2,
} 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
}

// ── Main Page ──

export default function ModelosPage() {
  const router = useRouter()
  const [templates, setTemplates] = useState<Template[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [filterType, setFilterType] = useState('')
  const [filterArea, setFilterArea] = useState('')
  const [showFilters, setShowFilters] = useState(false)
  const [showCreateForm, setShowCreateForm] = useState(false)
  const [creating, setCreating] = useState(false)

  // Form state
  const [formName, setFormName] = useState('')
  const [formDescription, setFormDescription] = useState('')
  const [formType, setFormType] = useState('')
  const [formArea, setFormArea] = useState('')
  const [formPrompt, setFormPrompt] = useState('')
  const [formError, setFormError] = useState('')

  const fetchTemplates = useCallback(async () => {
    setLoading(true)
    try {
      const params = new URLSearchParams()
      if (search) params.set('search', search)
      if (filterType) params.set('type', filterType)
      if (filterArea) params.set('area', filterArea)

      const res = await fetch(`/api/templates?${params.toString()}`)
      if (res.ok) {
        const data = await res.json()
        setTemplates(data.templates)
      }
    } catch {
      // silent
    } finally {
      setLoading(false)
    }
  }, [search, filterType, filterArea])

  useEffect(() => {
    const timeout = setTimeout(fetchTemplates, 300)
    return () => clearTimeout(timeout)
  }, [fetchTemplates])

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault()
    setFormError('')

    if (!formName || !formDescription || !formType || !formArea || !formPrompt) {
      setFormError('Preencha todos os campos.')
      return
    }

    setCreating(true)
    try {
      const res = await fetch('/api/templates', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: formName,
          description: formDescription,
          type: formType,
          area: formArea,
          prompt: formPrompt,
        }),
      })

      if (!res.ok) {
        const data = await res.json()
        setFormError(data.error || 'Erro ao criar modelo.')
        return
      }

      // Reset and refresh
      setFormName('')
      setFormDescription('')
      setFormType('')
      setFormArea('')
      setFormPrompt('')
      setShowCreateForm(false)
      fetchTemplates()
    } catch {
      setFormError('Erro de conexão.')
    } finally {
      setCreating(false)
    }
  }

  const handleUseTemplate = (template: Template) => {
    const params = new URLSearchParams({
      templateId: template.id,
      type: template.type,
      area: template.area,
      templateName: template.name,
    })
    router.push(`/dashboard/nova-peca?${params.toString()}`)
  }

  const activeFilters = (filterType ? 1 : 0) + (filterArea ? 1 : 0)
  const publicTemplates = templates.filter((t) => t.isPublic)
  const userTemplates = templates.filter((t) => !t.isPublic)

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="flex items-center gap-3 text-2xl font-bold text-white">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-teal-600/20">
              <BookTemplate className="h-5 w-5 text-teal-400" />
            </div>
            Modelos
          </h1>
          <p className="mt-1 text-sm text-zinc-400">
            Use modelos prontos ou crie os seus para agilizar a geração de peças.
          </p>
        </div>
        <button
          onClick={() => setShowCreateForm(true)}
          className="flex items-center gap-2 rounded-xl bg-teal-600 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-teal-600/20 transition-all hover:bg-teal-500 hover:shadow-teal-500/30"
        >
          <Plus className="h-4 w-4" />
          Criar Modelo
        </button>
      </div>

      {/* Search & Filters */}
      <div className="flex flex-col gap-3 sm:flex-row">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-500" />
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Buscar modelos..."
            className="w-full rounded-xl border border-white/10 bg-white/5 py-2.5 pl-10 pr-4 text-sm text-white placeholder-zinc-500 outline-none transition-colors focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/25"
          />
        </div>
        <button
          onClick={() => setShowFilters(!showFilters)}
          className={`flex items-center gap-2 rounded-xl border px-4 py-2.5 text-sm font-medium transition-colors ${
            showFilters || activeFilters > 0
              ? 'border-teal-500/50 bg-teal-600/10 text-teal-400'
              : 'border-white/10 bg-white/5 text-zinc-400 hover:border-white/20 hover:text-zinc-300'
          }`}
        >
          <Filter className="h-4 w-4" />
          Filtros
          {activeFilters > 0 && (
            <span className="flex h-5 w-5 items-center justify-center rounded-full bg-teal-600 text-[10px] font-bold text-white">
              {activeFilters}
            </span>
          )}
        </button>
      </div>

      {/* Filter Dropdowns */}
      {showFilters && (
        <div className="flex flex-wrap gap-3 rounded-xl border border-white/10 bg-white/[0.02] p-4">
          <div className="min-w-[180px] flex-1">
            <label className="mb-1.5 block text-xs font-medium text-zinc-400">Tipo</label>
            <select
              value={filterType}
              onChange={(e) => setFilterType(e.target.value)}
              className="w-full rounded-lg border border-white/10 bg-[#0f1620] px-3 py-2 text-sm text-white outline-none focus:border-teal-500/50"
            >
              <option value="">Todos os tipos</option>
              {TYPE_OPTIONS.map((t) => (
                <option key={t.value} value={t.value}>
                  {t.label}
                </option>
              ))}
            </select>
          </div>
          <div className="min-w-[180px] flex-1">
            <label className="mb-1.5 block text-xs font-medium text-zinc-400">Área</label>
            <select
              value={filterArea}
              onChange={(e) => setFilterArea(e.target.value)}
              className="w-full rounded-lg border border-white/10 bg-[#0f1620] px-3 py-2 text-sm text-white outline-none focus:border-teal-500/50"
            >
              <option value="">Todas as áreas</option>
              {AREA_OPTIONS.map((a) => (
                <option key={a.value} value={a.value}>
                  {a.label}
                </option>
              ))}
            </select>
          </div>
          {activeFilters > 0 && (
            <button
              onClick={() => {
                setFilterType('')
                setFilterArea('')
              }}
              className="flex items-center gap-1 self-end rounded-lg px-3 py-2 text-xs text-zinc-400 hover:text-red-400"
            >
              <X className="h-3 w-3" />
              Limpar filtros
            </button>
          )}
        </div>
      )}

      {/* Loading */}
      {loading && (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="h-8 w-8 animate-spin text-teal-500" />
        </div>
      )}

      {/* Empty State */}
      {!loading && templates.length === 0 && (
        <div className="flex flex-col items-center justify-center rounded-2xl border border-white/5 bg-white/[0.02] py-20">
          <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-teal-600/10">
            <BookTemplate className="h-8 w-8 text-teal-500/60" />
          </div>
          <h3 className="mt-4 text-lg font-semibold text-white">Nenhum modelo encontrado</h3>
          <p className="mt-1 text-sm text-zinc-500">
            {search || filterType || filterArea
              ? 'Tente ajustar seus filtros de busca.'
              : 'Crie seu primeiro modelo personalizado.'}
          </p>
          {!search && !filterType && !filterArea && (
            <button
              onClick={() => setShowCreateForm(true)}
              className="mt-4 flex items-center gap-2 rounded-xl bg-teal-600 px-5 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-teal-500"
            >
              <Plus className="h-4 w-4" />
              Criar Modelo
            </button>
          )}
        </div>
      )}

      {/* Public Templates */}
      {!loading && publicTemplates.length > 0 && (
        <section>
          <div className="mb-4 flex items-center gap-2">
            <Globe className="h-4 w-4 text-teal-400" />
            <h2 className="text-sm font-semibold uppercase tracking-wider text-zinc-400">
              Modelos do Sistema
            </h2>
            <span className="rounded-full bg-teal-600/15 px-2 py-0.5 text-[10px] font-bold text-teal-400">
              {publicTemplates.length}
            </span>
          </div>
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {publicTemplates.map((template) => (
              <TemplateCard
                key={template.id}
                template={template}
                onUse={() => handleUseTemplate(template)}
              />
            ))}
          </div>
        </section>
      )}

      {/* User Templates */}
      {!loading && userTemplates.length > 0 && (
        <section>
          <div className="mb-4 flex items-center gap-2">
            <User className="h-4 w-4 text-emerald-400" />
            <h2 className="text-sm font-semibold uppercase tracking-wider text-zinc-400">
              Meus Modelos
            </h2>
            <span className="rounded-full bg-emerald-600/15 px-2 py-0.5 text-[10px] font-bold text-emerald-400">
              {userTemplates.length}
            </span>
          </div>
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {userTemplates.map((template) => (
              <TemplateCard
                key={template.id}
                template={template}
                onUse={() => handleUseTemplate(template)}
                isOwn
              />
            ))}
          </div>
        </section>
      )}

      {/* Create Modal */}
      {showCreateForm && (
        <CreateTemplateModal
          formName={formName}
          setFormName={setFormName}
          formDescription={formDescription}
          setFormDescription={setFormDescription}
          formType={formType}
          setFormType={setFormType}
          formArea={formArea}
          setFormArea={setFormArea}
          formPrompt={formPrompt}
          setFormPrompt={setFormPrompt}
          formError={formError}
          creating={creating}
          onSubmit={handleCreate}
          onClose={() => {
            setShowCreateForm(false)
            setFormError('')
          }}
        />
      )}
    </div>
  )
}

// ── Template Card ──

function TemplateCard({
  template,
  onUse,
  isOwn,
}: {
  template: Template
  onUse: () => void
  isOwn?: boolean
}) {
  // Extract {{variables}} from prompt
  const variables = template.prompt.match(/\{\{(\w+)\}\}/g)?.map((v) => v.slice(2, -2)) ?? []

  return (
    <div className="group relative flex flex-col rounded-2xl border border-white/5 bg-white/[0.02] p-5 transition-all duration-200 hover:border-teal-500/30 hover:bg-teal-600/[0.04] hover:shadow-lg hover:shadow-teal-600/5">
      {/* Badges */}
      <div className="mb-3 flex flex-wrap gap-2">
        <span
          className={`rounded-lg border px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide ${
            TYPE_COLORS[template.type] ?? TYPE_COLORS.OUTROS
          }`}
        >
          {getTypeLabel(template.type)}
        </span>
        <span
          className={`rounded-lg border px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide ${
            AREA_COLORS[template.area] ?? AREA_COLORS.CIVIL
          }`}
        >
          {getAreaLabel(template.area)}
        </span>
        {isOwn && (
          <span className="rounded-lg border border-emerald-500/30 bg-emerald-500/15 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-emerald-400">
            Meu
          </span>
        )}
      </div>

      {/* Name & Description */}
      <h3 className="text-base font-semibold text-white group-hover:text-teal-300 transition-colors">
        {template.name}
      </h3>
      <p className="mt-1.5 flex-1 text-sm leading-relaxed text-zinc-500 line-clamp-2">
        {template.description}
      </p>

      {/* Variables preview */}
      {variables.length > 0 && (
        <div className="mt-3 flex flex-wrap gap-1.5">
          {variables.slice(0, 4).map((v) => (
            <span
              key={v}
              className="flex items-center gap-1 rounded-md bg-zinc-800/80 px-1.5 py-0.5 text-[10px] font-mono text-zinc-400"
            >
              <Code2 className="h-2.5 w-2.5" />
              {v}
            </span>
          ))}
          {variables.length > 4 && (
            <span className="rounded-md bg-zinc-800/80 px-1.5 py-0.5 text-[10px] text-zinc-500">
              +{variables.length - 4}
            </span>
          )}
        </div>
      )}

      {/* Actions */}
      <div className="mt-4 flex items-center gap-2">
        <button
          onClick={onUse}
          className="flex flex-1 items-center justify-center gap-2 rounded-xl bg-teal-600/15 py-2 text-sm font-semibold text-teal-400 transition-all hover:bg-teal-600 hover:text-white hover:shadow-lg hover:shadow-teal-600/20"
        >
          <Sparkles className="h-3.5 w-3.5" />
          Usar modelo
        </button>
        <Link
          href={`/dashboard/modelos/${template.id}`}
          className="flex items-center justify-center rounded-xl border border-white/10 p-2 text-zinc-400 transition-colors hover:border-white/20 hover:text-white"
        >
          <FileText className="h-4 w-4" />
        </Link>
      </div>
    </div>
  )
}

// ── Create Modal ──

function CreateTemplateModal({
  formName,
  setFormName,
  formDescription,
  setFormDescription,
  formType,
  setFormType,
  formArea,
  setFormArea,
  formPrompt,
  setFormPrompt,
  formError,
  creating,
  onSubmit,
  onClose,
}: {
  formName: string
  setFormName: (v: string) => void
  formDescription: string
  setFormDescription: (v: string) => void
  formType: string
  setFormType: (v: string) => void
  formArea: string
  setFormArea: (v: string) => void
  formPrompt: string
  setFormPrompt: (v: string) => void
  formError: string
  creating: boolean
  onSubmit: (e: React.FormEvent) => void
  onClose: () => void
}) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/70 backdrop-blur-sm" onClick={onClose} />

      {/* Modal */}
      <div className="relative w-full max-w-2xl rounded-2xl border border-white/10 bg-[#0f1620] p-6 shadow-2xl">
        <div className="mb-6 flex items-center justify-between">
          <h2 className="flex items-center gap-2 text-xl font-bold text-white">
            <Plus className="h-5 w-5 text-teal-400" />
            Criar Modelo Personalizado
          </h2>
          <button
            onClick={onClose}
            className="rounded-lg p-1.5 text-zinc-400 transition-colors hover:bg-white/5 hover:text-white"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        <form onSubmit={onSubmit} className="space-y-4">
          {/* Name */}
          <div>
            <label className="mb-1.5 block text-sm font-medium text-zinc-300">Nome do modelo</label>
            <input
              type="text"
              value={formName}
              onChange={(e) => setFormName(e.target.value)}
              placeholder="Ex: Petição de Danos Morais"
              className="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white placeholder-zinc-500 outline-none focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/25"
            />
          </div>

          {/* Description */}
          <div>
            <label className="mb-1.5 block text-sm font-medium text-zinc-300">Descrição</label>
            <input
              type="text"
              value={formDescription}
              onChange={(e) => setFormDescription(e.target.value)}
              placeholder="Breve descrição do que este modelo gera"
              className="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white placeholder-zinc-500 outline-none focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/25"
            />
          </div>

          {/* Type & Area */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="mb-1.5 block text-sm font-medium text-zinc-300">Tipo</label>
              <select
                value={formType}
                onChange={(e) => setFormType(e.target.value)}
                className="w-full rounded-xl border border-white/10 bg-[#0a1018] px-4 py-2.5 text-sm text-white outline-none focus:border-teal-500/50"
              >
                <option value="">Selecione o tipo</option>
                {TYPE_OPTIONS.map((t) => (
                  <option key={t.value} value={t.value}>
                    {t.label}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="mb-1.5 block text-sm font-medium text-zinc-300">Área</label>
              <select
                value={formArea}
                onChange={(e) => setFormArea(e.target.value)}
                className="w-full rounded-xl border border-white/10 bg-[#0a1018] px-4 py-2.5 text-sm text-white outline-none focus:border-teal-500/50"
              >
                <option value="">Selecione a área</option>
                {AREA_OPTIONS.map((a) => (
                  <option key={a.value} value={a.value}>
                    {a.label}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Prompt Template */}
          <div>
            <label className="mb-1.5 block text-sm font-medium text-zinc-300">
              Template do Prompt
            </label>
            <p className="mb-2 text-xs text-zinc-500">
              Use <code className="rounded bg-zinc-800 px-1 py-0.5 font-mono text-teal-400">{'{{variavel}}'}</code> para variáveis
              dinâmicas. Ex:{' '}
              <code className="rounded bg-zinc-800 px-1 py-0.5 font-mono text-teal-400">{'{{nome_autor}}'}</code>,{' '}
              <code className="rounded bg-zinc-800 px-1 py-0.5 font-mono text-teal-400">{'{{valor_causa}}'}</code>
            </p>
            <textarea
              value={formPrompt}
              onChange={(e) => setFormPrompt(e.target.value)}
              placeholder={`Elabore uma petição inicial de indenização por danos morais em face de {{nome_reu}}, em favor de {{nome_autor}}, no valor de {{valor_causa}}.\n\nFatos: {{fatos}}\n\nFundamentos jurídicos: CDC, art. 14 e CC, art. 186.`}
              rows={6}
              className="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 font-mono text-sm text-white placeholder-zinc-600 outline-none focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/25"
            />
          </div>

          {/* Error */}
          {formError && (
            <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-2.5 text-sm text-red-400">
              {formError}
            </div>
          )}

          {/* Actions */}
          <div className="flex justify-end gap-3 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="rounded-xl border border-white/10 px-5 py-2.5 text-sm font-medium text-zinc-400 transition-colors hover:bg-white/5 hover:text-white"
            >
              Cancelar
            </button>
            <button
              type="submit"
              disabled={creating}
              className="flex items-center gap-2 rounded-xl bg-teal-600 px-6 py-2.5 text-sm font-semibold text-white shadow-lg shadow-teal-600/20 transition-all hover:bg-teal-500 disabled:opacity-50"
            >
              {creating ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Criando...
                </>
              ) : (
                <>
                  <Plus className="h-4 w-4" />
                  Criar Modelo
                </>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
