'use client'

import { useState, useCallback, useEffect } from 'react'
import {
  Search,
  Filter,
  ChevronDown,
  ChevronUp,
  Copy,
  Check,
  Sparkles,
  Scale,
  Calendar,
  User,
  Tag,
  X,
  Loader2,
  ChevronLeft,
  ChevronRight,
  Brain,
  Zap,
} from 'lucide-react'

// ── Types ────────────────────────────────────────────────────────────

interface Jurisprudencia {
  id: string
  tribunal: string
  numero: string
  ementa: string
  data: string
  area: string
  relator: string
  orgaoJulgador: string
  tags: string
}

interface SearchResponse {
  results: Jurisprudencia[]
  total: number
  page: number
  perPage: number
  totalPages: number
}

interface AISearchResponse {
  results: Jurisprudencia[]
  total: number
  extractedTerms: {
    keywords: string[]
    tribunal?: string
    area?: string
    relator?: string
  }
  aiQuery: string
}

// ── Constants ────────────────────────────────────────────────────────

const TRIBUNAIS = [
  'STF', 'STJ', 'TST',
  'TRF1', 'TRF2', 'TRF3', 'TRF4', 'TRF5',
  'TJSP', 'TJRJ', 'TJMG', 'TJRS', 'TJPR', 'TJSC',
  'TJBA', 'TJPE', 'TJCE', 'TJGO', 'TJDF', 'TJES',
  'TJMT', 'TJMS', 'TJPA', 'TJMA', 'TJPB', 'TJRN',
  'TJAL', 'TJSE', 'TJPI', 'TJTO', 'TJRO', 'TJAC',
  'TJAP', 'TJRR', 'TJAM',
]

const AREAS = [
  { 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 TRIBUNAL_COLORS: Record<string, string> = {
  STF: 'bg-emerald-500/20 text-emerald-400 border-emerald-500/30',
  STJ: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
  TST: 'bg-amber-500/20 text-amber-400 border-amber-500/30',
  TRF1: 'bg-rose-500/20 text-rose-400 border-rose-500/30',
  TRF2: 'bg-rose-500/20 text-rose-400 border-rose-500/30',
  TRF3: 'bg-rose-500/20 text-rose-400 border-rose-500/30',
  TRF4: 'bg-rose-500/20 text-rose-400 border-rose-500/30',
  TRF5: 'bg-rose-500/20 text-rose-400 border-rose-500/30',
}

function getTribunalColor(tribunal: string): string {
  if (TRIBUNAL_COLORS[tribunal]) return TRIBUNAL_COLORS[tribunal]
  if (tribunal.startsWith('TJ')) return 'bg-teal-500/20 text-teal-400 border-teal-500/30'
  return 'bg-zinc-500/20 text-zinc-400 border-zinc-500/30'
}

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

// ── Component ────────────────────────────────────────────────────────

export default function JurisprudenciaPage() {
  // Search state
  const [searchQuery, setSearchQuery] = useState('')
  const [aiQuery, setAiQuery] = useState('')
  const [isAIMode, setIsAIMode] = useState(false)
  const [showFilters, setShowFilters] = useState(false)

  // Filters
  const [tribunal, setTribunal] = useState('')
  const [area, setArea] = useState('')
  const [relator, setRelator] = useState('')
  const [dateFrom, setDateFrom] = useState('')
  const [dateTo, setDateTo] = useState('')

  // Results
  const [results, setResults] = useState<Jurisprudencia[]>([])
  const [total, setTotal] = useState(0)
  const [totalPages, setTotalPages] = useState(0)
  const [page, setPage] = useState(1)
  const [loading, setLoading] = useState(false)
  const [searched, setSearched] = useState(false)

  // AI extras
  const [extractedTerms, setExtractedTerms] = useState<AISearchResponse['extractedTerms'] | null>(null)

  // Expand state
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set())

  // Copy state
  const [copiedId, setCopiedId] = useState<string | null>(null)

  const activeFilterCount = [tribunal, area, relator, dateFrom, dateTo].filter(Boolean).length

  // ── Standard search ──

  const doSearch = useCallback(async (p = 1) => {
    setLoading(true)
    setSearched(true)
    setExtractedTerms(null)

    const params = new URLSearchParams()
    if (searchQuery) params.set('search', searchQuery)
    if (tribunal) params.set('tribunal', tribunal)
    if (area) params.set('area', area)
    if (relator) params.set('relator', relator)
    if (dateFrom) params.set('dateFrom', dateFrom)
    if (dateTo) params.set('dateTo', dateTo)
    params.set('page', p.toString())
    params.set('perPage', '10')

    try {
      const res = await fetch(`/api/jurisprudencia?${params.toString()}`)
      const data: SearchResponse = await res.json()
      setResults(data.results)
      setTotal(data.total)
      setTotalPages(data.totalPages)
      setPage(data.page)
    } catch (err) {
      console.error('Search error:', err)
    } finally {
      setLoading(false)
    }
  }, [searchQuery, tribunal, area, relator, dateFrom, dateTo])

  // ── AI search ──

  const doAISearch = useCallback(async () => {
    if (!aiQuery.trim()) return
    setLoading(true)
    setSearched(true)

    try {
      const res = await fetch('/api/jurisprudencia/search', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query: aiQuery }),
      })
      const data: AISearchResponse = await res.json()
      setResults(data.results)
      setTotal(data.total)
      setTotalPages(1)
      setPage(1)
      setExtractedTerms(data.extractedTerms)
    } catch (err) {
      console.error('AI search error:', err)
    } finally {
      setLoading(false)
    }
  }, [aiQuery])

  // ── Handlers ──

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault()
    if (isAIMode) {
      doAISearch()
    } else {
      doSearch(1)
    }
  }

  const handlePageChange = (newPage: number) => {
    if (newPage < 1 || newPage > totalPages) return
    doSearch(newPage)
  }

  const toggleExpand = (id: string) => {
    setExpandedIds((prev) => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const copyCitation = (item: Jurisprudencia) => {
    const tags = parseTags(item.tags)
    const citation = `${item.tribunal} - ${item.numero} - Rel. ${item.relator} - ${item.orgaoJulgador} - ${formatDate(item.data)}${tags.length ? ` - ${tags.join(', ')}` : ''}\n\nEMENTA: ${item.ementa}`
    navigator.clipboard.writeText(citation)
    setCopiedId(item.id)
    setTimeout(() => setCopiedId(null), 2000)
  }

  const clearFilters = () => {
    setTribunal('')
    setArea('')
    setRelator('')
    setDateFrom('')
    setDateTo('')
  }

  // ── Helpers ──

  const formatDate = (dateStr: string) => {
    try {
      const [y, m, d] = dateStr.split('-')
      return `${d}/${m}/${y}`
    } catch {
      return dateStr
    }
  }

  const parseTags = (tagsStr: string): string[] => {
    try {
      return JSON.parse(tagsStr)
    } catch {
      return []
    }
  }

  const truncateEmenta = (text: string, max = 250) => {
    if (text.length <= max) return text
    return text.slice(0, max).trimEnd() + '…'
  }

  // Load initial results on mount
  useEffect(() => {
    doSearch(1)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <div className="space-y-6">
      {/* ── Header ── */}
      <div>
        <h1 className="text-2xl font-bold text-white">Jurisprudência</h1>
        <p className="mt-1 text-sm text-zinc-400">
          Pesquise decisões judiciais de tribunais brasileiros
        </p>
      </div>

      {/* ── Search Mode Toggle ── */}
      <div className="flex items-center gap-2">
        <button
          onClick={() => setIsAIMode(false)}
          className={`flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-all ${
            !isAIMode
              ? 'bg-teal-600 text-white shadow-lg shadow-teal-500/20'
              : 'bg-white/5 text-zinc-400 hover:bg-white/10 hover:text-zinc-200'
          }`}
        >
          <Search className="h-4 w-4" />
          Busca Padrão
        </button>
        <button
          onClick={() => setIsAIMode(true)}
          className={`flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-all ${
            isAIMode
              ? 'bg-gradient-to-r from-teal-600 to-teal-600 text-white shadow-lg shadow-teal-500/20'
              : 'bg-white/5 text-zinc-400 hover:bg-white/10 hover:text-zinc-200'
          }`}
        >
          <Brain className="h-4 w-4" />
          Busca Inteligente
          <Sparkles className="h-3 w-3 text-amber-400" />
        </button>
      </div>

      {/* ── Search Bar ── */}
      <form onSubmit={handleSearch} className="space-y-3">
        <div className="relative">
          <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-4">
            {isAIMode ? (
              <Sparkles className="h-5 w-5 text-teal-400" />
            ) : (
              <Search className="h-5 w-5 text-zinc-500" />
            )}
          </div>
          <input
            type="text"
            value={isAIMode ? aiQuery : searchQuery}
            onChange={(e) =>
              isAIMode ? setAiQuery(e.target.value) : setSearchQuery(e.target.value)
            }
            placeholder={
              isAIMode
                ? 'Ex: "jurisprudência sobre dano moral em relações de consumo no STJ"'
                : 'Pesquisar por ementa, número do processo ou relator...'
            }
            className={`w-full rounded-xl border bg-white/5 py-3.5 pl-12 pr-32 text-sm text-white placeholder-zinc-500 transition-all focus:outline-none ${
              isAIMode
                ? 'border-teal-500/30 focus:border-teal-500/60 focus:ring-2 focus:ring-teal-500/20'
                : 'border-white/10 focus:border-teal-500/40 focus:ring-2 focus:ring-teal-500/10'
            }`}
          />
          <div className="absolute inset-y-0 right-0 flex items-center gap-2 pr-2">
            {!isAIMode && (
              <button
                type="button"
                onClick={() => setShowFilters(!showFilters)}
                className={`flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium transition-all ${
                  showFilters || activeFilterCount > 0
                    ? 'bg-teal-600/20 text-teal-400'
                    : 'bg-white/5 text-zinc-400 hover:bg-white/10'
                }`}
              >
                <Filter className="h-3.5 w-3.5" />
                Filtros
                {activeFilterCount > 0 && (
                  <span className="flex h-4 w-4 items-center justify-center rounded-full bg-teal-600 text-[10px] font-bold text-white">
                    {activeFilterCount}
                  </span>
                )}
              </button>
            )}
            <button
              type="submit"
              disabled={loading}
              className="flex items-center gap-2 rounded-lg bg-teal-600 px-4 py-1.5 text-sm font-medium text-white transition-colors hover:bg-teal-500 disabled:opacity-50"
            >
              {loading ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : isAIMode ? (
                <Zap className="h-4 w-4" />
              ) : (
                <Search className="h-4 w-4" />
              )}
              Buscar
            </button>
          </div>
        </div>

        {/* ── Filters Panel ── */}
        {showFilters && !isAIMode && (
          <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
            <div className="flex items-center justify-between">
              <span className="text-xs font-semibold uppercase tracking-wider text-zinc-500">
                Filtros avançados
              </span>
              {activeFilterCount > 0 && (
                <button
                  type="button"
                  onClick={clearFilters}
                  className="flex items-center gap-1 text-xs text-zinc-500 hover:text-zinc-300"
                >
                  <X className="h-3 w-3" />
                  Limpar filtros
                </button>
              )}
            </div>
            <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
              {/* Tribunal */}
              <div>
                <label className="mb-1 flex items-center gap-1.5 text-xs font-medium text-zinc-400">
                  <Scale className="h-3 w-3" />
                  Tribunal
                </label>
                <select
                  value={tribunal}
                  onChange={(e) => setTribunal(e.target.value)}
                  className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-white focus:border-teal-500/40 focus:outline-none focus:ring-2 focus:ring-teal-500/10"
                >
                  <option value="" className="bg-[#0f1620]">Todos</option>
                  {TRIBUNAIS.map((t) => (
                    <option key={t} value={t} className="bg-[#0f1620]">
                      {t}
                    </option>
                  ))}
                </select>
              </div>

              {/* Área */}
              <div>
                <label className="mb-1 flex items-center gap-1.5 text-xs font-medium text-zinc-400">
                  <Tag className="h-3 w-3" />
                  Área do Direito
                </label>
                <select
                  value={area}
                  onChange={(e) => setArea(e.target.value)}
                  className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-white focus:border-teal-500/40 focus:outline-none focus:ring-2 focus:ring-teal-500/10"
                >
                  <option value="" className="bg-[#0f1620]">Todas</option>
                  {AREAS.map((a) => (
                    <option key={a.value} value={a.value} className="bg-[#0f1620]">
                      {a.label}
                    </option>
                  ))}
                </select>
              </div>

              {/* Relator */}
              <div>
                <label className="mb-1 flex items-center gap-1.5 text-xs font-medium text-zinc-400">
                  <User className="h-3 w-3" />
                  Relator
                </label>
                <input
                  type="text"
                  value={relator}
                  onChange={(e) => setRelator(e.target.value)}
                  placeholder="Nome do relator..."
                  className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-white placeholder-zinc-600 focus:border-teal-500/40 focus:outline-none focus:ring-2 focus:ring-teal-500/10"
                />
              </div>

              {/* Date range */}
              <div>
                <label className="mb-1 flex items-center gap-1.5 text-xs font-medium text-zinc-400">
                  <Calendar className="h-3 w-3" />
                  Período
                </label>
                <div className="flex items-center gap-2">
                  <input
                    type="date"
                    value={dateFrom}
                    onChange={(e) => setDateFrom(e.target.value)}
                    className="w-full rounded-lg border border-white/10 bg-white/5 px-2 py-2 text-xs text-white focus:border-teal-500/40 focus:outline-none focus:ring-2 focus:ring-teal-500/10 [color-scheme:dark]"
                  />
                  <span className="text-zinc-600">—</span>
                  <input
                    type="date"
                    value={dateTo}
                    onChange={(e) => setDateTo(e.target.value)}
                    className="w-full rounded-lg border border-white/10 bg-white/5 px-2 py-2 text-xs text-white focus:border-teal-500/40 focus:outline-none focus:ring-2 focus:ring-teal-500/10 [color-scheme:dark]"
                  />
                </div>
              </div>
            </div>
          </div>
        )}
      </form>

      {/* ── AI Extracted Terms ── */}
      {extractedTerms && (
        <div className="flex flex-wrap items-center gap-2 rounded-xl border border-teal-500/20 bg-teal-500/5 p-3">
          <span className="flex items-center gap-1.5 text-xs font-medium text-teal-400">
            <Brain className="h-3.5 w-3.5" />
            Termos extraídos pela IA:
          </span>
          {extractedTerms.keywords.map((kw, i) => (
            <span
              key={i}
              className="rounded-md bg-teal-500/15 px-2 py-0.5 text-xs font-medium text-teal-300"
            >
              {kw}
            </span>
          ))}
          {extractedTerms.tribunal && (
            <span className="rounded-md bg-blue-500/15 px-2 py-0.5 text-xs font-medium text-blue-300">
              Tribunal: {extractedTerms.tribunal}
            </span>
          )}
          {extractedTerms.area && (
            <span className="rounded-md bg-emerald-500/15 px-2 py-0.5 text-xs font-medium text-emerald-300">
              Área: {extractedTerms.area}
            </span>
          )}
        </div>
      )}

      {/* ── Results ── */}
      {loading ? (
        <div className="flex flex-col items-center justify-center py-20">
          <Loader2 className="h-8 w-8 animate-spin text-teal-500" />
          <p className="mt-3 text-sm text-zinc-500">
            {isAIMode ? 'IA analisando sua consulta...' : 'Buscando jurisprudência...'}
          </p>
        </div>
      ) : searched && results.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-20">
          <Scale className="h-12 w-12 text-zinc-700" />
          <p className="mt-3 text-sm font-medium text-zinc-400">
            Nenhuma jurisprudência encontrada
          </p>
          <p className="mt-1 text-xs text-zinc-600">
            Tente ajustar os termos de busca ou os filtros
          </p>
        </div>
      ) : (
        <>
          {/* Result count */}
          {searched && (
            <div className="flex items-center justify-between">
              <p className="text-sm text-zinc-500">
                <span className="font-medium text-zinc-300">{total}</span>{' '}
                resultado{total !== 1 ? 's' : ''} encontrado{total !== 1 ? 's' : ''}
              </p>
            </div>
          )}

          {/* Cards */}
          <div className="space-y-3">
            {results.map((item) => {
              const isExpanded = expandedIds.has(item.id)
              const isCopied = copiedId === item.id
              const tags = parseTags(item.tags)
              const areaLabel = AREAS.find((a) => a.value === item.area)?.label || item.area

              return (
                <div
                  key={item.id}
                  className="group rounded-xl border border-white/5 bg-white/[0.02] transition-all hover:border-white/10 hover:bg-white/[0.04]"
                >
                  <div className="p-5">
                    {/* Top row */}
                    <div className="flex flex-wrap items-start justify-between gap-3">
                      <div className="flex flex-wrap items-center gap-2">
                        {/* Tribunal badge */}
                        <span
                          className={`rounded-md border px-2.5 py-1 text-xs font-bold tracking-wide ${getTribunalColor(
                            item.tribunal
                          )}`}
                        >
                          {item.tribunal}
                        </span>
                        {/* Process number */}
                        <span className="text-sm font-semibold text-white">
                          {item.numero}
                        </span>
                      </div>
                      {/* Date */}
                      <span className="flex items-center gap-1.5 text-xs text-zinc-500">
                        <Calendar className="h-3 w-3" />
                        {formatDate(item.data)}
                      </span>
                    </div>

                    {/* Relator & Órgão */}
                    <div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-zinc-500">
                      <span className="flex items-center gap-1">
                        <User className="h-3 w-3" />
                        Rel. {item.relator}
                      </span>
                      {item.orgaoJulgador && (
                        <span className="text-zinc-600">• {item.orgaoJulgador}</span>
                      )}
                    </div>

                    {/* Ementa */}
                    <div className="mt-3">
                      <p className="text-sm leading-relaxed text-zinc-300">
                        {isExpanded ? item.ementa : truncateEmenta(item.ementa)}
                      </p>
                      {item.ementa.length > 250 && (
                        <button
                          onClick={() => toggleExpand(item.id)}
                          className="mt-1.5 flex items-center gap-1 text-xs font-medium text-teal-400 hover:text-teal-300"
                        >
                          {isExpanded ? (
                            <>
                              <ChevronUp className="h-3 w-3" />
                              Mostrar menos
                            </>
                          ) : (
                            <>
                              <ChevronDown className="h-3 w-3" />
                              Ler ementa completa
                            </>
                          )}
                        </button>
                      )}
                    </div>

                    {/* Tags & Actions */}
                    <div className="mt-3 flex flex-wrap items-center justify-between gap-2">
                      <div className="flex flex-wrap items-center gap-1.5">
                        <span
                          className={`rounded-md px-2 py-0.5 text-[11px] font-medium ${
                            AREA_COLORS[item.area] || 'bg-zinc-500/15 text-zinc-400'
                          }`}
                        >
                          {areaLabel}
                        </span>
                        {tags.map((tag, i) => (
                          <span
                            key={i}
                            className="rounded-md bg-white/5 px-2 py-0.5 text-[11px] text-zinc-500"
                          >
                            {tag}
                          </span>
                        ))}
                      </div>
                      <button
                        onClick={() => copyCitation(item)}
                        className={`flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium transition-all ${
                          isCopied
                            ? 'bg-emerald-500/20 text-emerald-400'
                            : 'bg-teal-600/15 text-teal-400 hover:bg-teal-600/25'
                        }`}
                      >
                        {isCopied ? (
                          <>
                            <Check className="h-3.5 w-3.5" />
                            Copiado!
                          </>
                        ) : (
                          <>
                            <Copy className="h-3.5 w-3.5" />
                            Usar em peça
                          </>
                        )}
                      </button>
                    </div>
                  </div>
                </div>
              )
            })}
          </div>

          {/* ── Pagination ── */}
          {totalPages > 1 && !isAIMode && (
            <div className="flex items-center justify-center gap-2 pt-4">
              <button
                onClick={() => handlePageChange(page - 1)}
                disabled={page <= 1}
                className="flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-zinc-400 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-30"
              >
                <ChevronLeft className="h-4 w-4" />
                Anterior
              </button>

              <div className="flex items-center gap-1">
                {Array.from({ length: Math.min(totalPages, 7) }, (_, i) => {
                  let pageNum: number
                  if (totalPages <= 7) {
                    pageNum = i + 1
                  } else if (page <= 4) {
                    pageNum = i + 1
                  } else if (page >= totalPages - 3) {
                    pageNum = totalPages - 6 + i
                  } else {
                    pageNum = page - 3 + i
                  }

                  return (
                    <button
                      key={pageNum}
                      onClick={() => handlePageChange(pageNum)}
                      className={`flex h-9 w-9 items-center justify-center rounded-lg text-sm font-medium transition-all ${
                        pageNum === page
                          ? 'bg-teal-600 text-white shadow-lg shadow-teal-500/20'
                          : 'text-zinc-500 hover:bg-white/5 hover:text-zinc-300'
                      }`}
                    >
                      {pageNum}
                    </button>
                  )
                })}
              </div>

              <button
                onClick={() => handlePageChange(page + 1)}
                disabled={page >= totalPages}
                className="flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-zinc-400 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-30"
              >
                Próxima
                <ChevronRight className="h-4 w-4" />
              </button>
            </div>
          )}
        </>
      )}
    </div>
  )
}
