'use client'

import { useState, useEffect, useCallback } from 'react'
import FileUpload from '@/components/FileUpload'
import { useRouter } from 'next/navigation'
import { motion, AnimatePresence } from 'framer-motion'
import {
  FileText, Search, Filter, Grid3X3, List, Eye, Copy, Trash2, Upload,
  ChevronDown, Calendar, ArrowUpDown, Plus, Loader2, AlertTriangle,
  CheckCircle2, Clock, X
} from 'lucide-react'

// ── Constants ──

const DOCUMENT_TYPES: Record<string, string> = {
  PETICAO_INICIAL: 'Petição Inicial',
  CONTESTACAO: 'Contestação',
  APELACAO: 'Apelação',
  RECURSO: 'Recurso',
  CONTRATO: 'Contrato',
  PARECER: 'Parecer',
  IMPUGNACAO: 'Impugnação',
  HABEAS_CORPUS: 'Habeas Corpus',
  MANDADO_SEGURANCA: 'Mandado de Segurança',
  OUTROS: 'Outros',
}

const AREAS: Record<string, string> = {
  CIVIL: 'Civil',
  TRABALHISTA: 'Trabalhista',
  PENAL: 'Penal',
  TRIBUTARIO: 'Tributário',
  FAMILIA: 'Família',
  EMPRESARIAL: 'Empresarial',
  CONSUMIDOR: 'Consumidor',
  ADMINISTRATIVO: 'Administrativo',
}

const STATUS_CONFIG: Record<string, { label: string; color: string; icon: typeof CheckCircle2 }> = {
  COMPLETED: { label: 'Concluído', color: 'text-emerald-400 bg-emerald-400/10 border-emerald-400/20', icon: CheckCircle2 },
  GENERATING: { label: 'Gerando...', color: 'text-amber-400 bg-amber-400/10 border-amber-400/20', icon: Clock },
  ERROR: { label: 'Erro', color: 'text-red-400 bg-red-400/10 border-red-400/20', icon: AlertTriangle },
}

interface Document {
  id: string
  title: string
  type: string
  area: string
  status: string
  wordCount: number
  tokens: number
  cost: number
  createdAt: string
}

// ── Component ──

export default function MinhasPecasPage() {
  const router = useRouter()
  const [documents, setDocuments] = useState<Document[]>([])
  const [loading, setLoading] = useState(true)
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid')
  const [activeTab, setActiveTab] = useState<'documents' | 'uploads'>('documents')
  const [search, setSearch] = useState('')
  const [typeFilter, setTypeFilter] = useState('')
  const [areaFilter, setAreaFilter] = useState('')
  const [sort, setSort] = useState('newest')
  const [dateFrom, setDateFrom] = useState('')
  const [dateTo, setDateTo] = useState('')
  const [deleteId, setDeleteId] = useState<string | null>(null)
  const [deleting, setDeleting] = useState(false)
  const [copied, setCopied] = useState<string | null>(null)

  const fetchDocuments = useCallback(async () => {
    setLoading(true)
    const params = new URLSearchParams()
    if (search) params.set('search', search)
    if (typeFilter) params.set('type', typeFilter)
    if (areaFilter) params.set('area', areaFilter)
    if (sort) params.set('sort', sort)
    if (dateFrom) params.set('dateFrom', dateFrom)
    if (dateTo) params.set('dateTo', dateTo)

    try {
      const res = await fetch(`/api/documents?${params.toString()}`)
      const data = await res.json()
      setDocuments(data.documents || [])
    } catch {
      setDocuments([])
    } finally {
      setLoading(false)
    }
  }, [search, typeFilter, areaFilter, sort, dateFrom, dateTo])

  useEffect(() => {
    const timer = setTimeout(fetchDocuments, 300)
    return () => clearTimeout(timer)
  }, [fetchDocuments])

  const handleDelete = async () => {
    if (!deleteId) return
    setDeleting(true)
    try {
      await fetch(`/api/documents/${deleteId}`, { method: 'DELETE' })
      setDocuments(prev => prev.filter(d => d.id !== deleteId))
    } finally {
      setDeleting(false)
      setDeleteId(null)
    }
  }

  const handleCopy = async (id: string) => {
    try {
      const res = await fetch(`/api/documents/${id}`)
      const { document } = await res.json()
      await navigator.clipboard.writeText(document.content)
      setCopied(id)
      setTimeout(() => setCopied(null), 2000)
    } catch { /* ignore */ }
  }

  const formatDate = (date: string) =>
    new Intl.DateTimeFormat('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric' }).format(new Date(date))

  const hasFilters = typeFilter || areaFilter || dateFrom || dateTo || search

  // ── Render ──
  return (
    <div className="min-h-screen bg-[#0a0f1a] p-4 md:p-8">
      {/* Header */}
      <div className="max-w-7xl mx-auto">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-8">
          <div>
            <h1 className="text-3xl font-bold gradient-text">Minhas Peças</h1>
            <p className="text-gray-400 mt-1">
              {loading ? 'Carregando...' : `${documents.length} documento${documents.length !== 1 ? 's' : ''}`}
            </p>
          </div>
          <button
            onClick={() => router.push('/dashboard/gerar')}
            className="flex items-center gap-2 px-6 py-3 bg-teal-600 hover:bg-teal-700 rounded-xl font-semibold transition-all glow-purple"
          >
            <Plus className="w-5 h-5" />
            Nova Peça
          </button>
        </div>

        {/* Tabs */}
        <div className="flex gap-2 mb-6">
          <button
            onClick={() => setActiveTab('documents')}
            className={`flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-medium transition-all ${
              activeTab === 'documents'
                ? 'bg-teal-600/20 text-teal-400 border border-teal-500/30'
                : 'bg-white/5 text-gray-400 border border-white/10 hover:text-white'
            }`}
          >
            <FileText className="w-4 h-4" />
            Documentos
          </button>
          <button
            onClick={() => setActiveTab('uploads')}
            className={`flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-medium transition-all ${
              activeTab === 'uploads'
                ? 'bg-teal-600/20 text-teal-400 border border-teal-500/30'
                : 'bg-white/5 text-gray-400 border border-white/10 hover:text-white'
            }`}
          >
            <Upload className="w-4 h-4" />
            Uploads
          </button>
        </div>

        {activeTab === 'uploads' ? (
          <div className="glass rounded-2xl p-6">
            <h2 className="text-lg font-semibold text-white mb-4">Meus Uploads</h2>
            <FileUpload label="Meus Uploads" maxFiles={50} />
          </div>
        ) : (
        <>
        {/* Filters Bar */}
        <div className="glass rounded-2xl p-4 mb-6 space-y-4">
          {/* Search + View Toggle */}
          <div className="flex flex-col md:flex-row gap-3">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="text"
                placeholder="Buscar por título..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="w-full pl-11 pr-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder-gray-500 focus:outline-none focus:border-teal-500/50 focus:ring-1 focus:ring-teal-500/30 transition-all"
              />
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => setViewMode('grid')}
                className={`p-3 rounded-xl border transition-all ${viewMode === 'grid' ? 'bg-teal-600/20 border-teal-500/40 text-teal-400' : 'bg-white/5 border-white/10 text-gray-400 hover:text-white'}`}
              >
                <Grid3X3 className="w-5 h-5" />
              </button>
              <button
                onClick={() => setViewMode('list')}
                className={`p-3 rounded-xl border transition-all ${viewMode === 'list' ? 'bg-teal-600/20 border-teal-500/40 text-teal-400' : 'bg-white/5 border-white/10 text-gray-400 hover:text-white'}`}
              >
                <List className="w-5 h-5" />
              </button>
            </div>
          </div>

          {/* Filter Dropdowns */}
          <div className="flex flex-wrap gap-3 items-center">
            <Filter className="w-4 h-4 text-gray-400" />

            {/* Type Filter */}
            <div className="relative">
              <select
                value={typeFilter}
                onChange={(e) => setTypeFilter(e.target.value)}
                className="appearance-none pl-3 pr-8 py-2 bg-white/5 border border-white/10 rounded-lg text-sm text-gray-300 focus:outline-none focus:border-teal-500/50 cursor-pointer"
              >
                <option value="">Todos os tipos</option>
                {Object.entries(DOCUMENT_TYPES).map(([key, label]) => (
                  <option key={key} value={key}>{label}</option>
                ))}
              </select>
              <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
            </div>

            {/* Area Filter */}
            <div className="relative">
              <select
                value={areaFilter}
                onChange={(e) => setAreaFilter(e.target.value)}
                className="appearance-none pl-3 pr-8 py-2 bg-white/5 border border-white/10 rounded-lg text-sm text-gray-300 focus:outline-none focus:border-teal-500/50 cursor-pointer"
              >
                <option value="">Todas as áreas</option>
                {Object.entries(AREAS).map(([key, label]) => (
                  <option key={key} value={key}>{label}</option>
                ))}
              </select>
              <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
            </div>

            {/* Sort */}
            <div className="relative">
              <select
                value={sort}
                onChange={(e) => setSort(e.target.value)}
                className="appearance-none pl-3 pr-8 py-2 bg-white/5 border border-white/10 rounded-lg text-sm text-gray-300 focus:outline-none focus:border-teal-500/50 cursor-pointer"
              >
                <option value="newest">Mais recentes</option>
                <option value="oldest">Mais antigos</option>
                <option value="type">Por tipo</option>
              </select>
              <ArrowUpDown className="absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
            </div>

            {/* Date Range */}
            <div className="flex items-center gap-2">
              <Calendar className="w-4 h-4 text-gray-400" />
              <input
                type="date"
                value={dateFrom}
                onChange={(e) => setDateFrom(e.target.value)}
                className="px-2 py-1.5 bg-white/5 border border-white/10 rounded-lg text-sm text-gray-300 focus:outline-none focus:border-teal-500/50"
              />
              <span className="text-gray-500 text-sm">até</span>
              <input
                type="date"
                value={dateTo}
                onChange={(e) => setDateTo(e.target.value)}
                className="px-2 py-1.5 bg-white/5 border border-white/10 rounded-lg text-sm text-gray-300 focus:outline-none focus:border-teal-500/50"
              />
            </div>

            {hasFilters && (
              <button
                onClick={() => { setSearch(''); setTypeFilter(''); setAreaFilter(''); setDateFrom(''); setDateTo(''); setSort('newest') }}
                className="flex items-center gap-1 px-3 py-1.5 text-xs text-red-400 hover:text-red-300 bg-red-400/10 border border-red-400/20 rounded-lg transition-all"
              >
                <X className="w-3 h-3" /> Limpar filtros
              </button>
            )}
          </div>
        </div>

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

        {/* Empty State */}
        {!loading && documents.length === 0 && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="flex flex-col items-center justify-center py-24 text-center"
          >
            <div className="w-20 h-20 rounded-2xl bg-teal-600/10 border border-teal-500/20 flex items-center justify-center mb-6">
              <FileText className="w-10 h-10 text-teal-400" />
            </div>
            <h2 className="text-xl font-semibold text-white mb-2">
              Nenhuma peça criada ainda
            </h2>
            <p className="text-gray-400 mb-6 max-w-md">
              Comece agora! Use nossa IA para gerar petições, contratos, pareceres e muito mais em segundos.
            </p>
            <button
              onClick={() => router.push('/dashboard/gerar')}
              className="flex items-center gap-2 px-6 py-3 bg-teal-600 hover:bg-teal-700 rounded-xl font-semibold transition-all glow-purple"
            >
              <Plus className="w-5 h-5" />
              Criar Primeira Peça
            </button>
          </motion.div>
        )}

        {/* Document Grid */}
        {!loading && documents.length > 0 && viewMode === 'grid' && (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <AnimatePresence mode="popLayout">
              {documents.map((doc, i) => {
                const status = STATUS_CONFIG[doc.status] || STATUS_CONFIG.COMPLETED
                const StatusIcon = status.icon
                return (
                  <motion.div
                    key={doc.id}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, scale: 0.95 }}
                    transition={{ delay: i * 0.05 }}
                    onClick={() => router.push(`/dashboard/minhas-pecas/${doc.id}`)}
                    className="glass rounded-2xl p-5 cursor-pointer hover:border-teal-500/30 transition-all group"
                  >
                    {/* Status & Date */}
                    <div className="flex items-center justify-between mb-3">
                      <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-full border ${status.color}`}>
                        <StatusIcon className="w-3 h-3" />
                        {status.label}
                      </span>
                      <span className="text-xs text-gray-500">{formatDate(doc.createdAt)}</span>
                    </div>

                    {/* Title */}
                    <h3 className="text-white font-semibold text-lg mb-3 line-clamp-2 group-hover:text-teal-300 transition-colors">
                      {doc.title}
                    </h3>

                    {/* Badges */}
                    <div className="flex flex-wrap gap-2 mb-4">
                      <span className="px-2.5 py-1 text-xs font-medium text-teal-300 bg-teal-500/10 border border-teal-500/20 rounded-full">
                        {DOCUMENT_TYPES[doc.type] || doc.type}
                      </span>
                      <span className="px-2.5 py-1 text-xs font-medium text-blue-300 bg-blue-500/10 border border-blue-500/20 rounded-full">
                        {AREAS[doc.area] || doc.area}
                      </span>
                    </div>

                    {/* Word Count */}
                    <p className="text-sm text-gray-400 mb-4">
                      {doc.wordCount.toLocaleString('pt-BR')} palavras
                    </p>

                    {/* Actions */}
                    <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity" onClick={(e) => e.stopPropagation()}>
                      <button
                        onClick={() => router.push(`/dashboard/minhas-pecas/${doc.id}`)}
                        className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-gray-300 hover:text-white bg-white/5 hover:bg-white/10 rounded-lg border border-white/10 transition-all"
                      >
                        <Eye className="w-3.5 h-3.5" /> Ver
                      </button>
                      <button
                        onClick={() => handleCopy(doc.id)}
                        className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-gray-300 hover:text-white bg-white/5 hover:bg-white/10 rounded-lg border border-white/10 transition-all"
                      >
                        <Copy className="w-3.5 h-3.5" /> {copied === doc.id ? 'Copiado!' : 'Copiar'}
                      </button>
                      <button
                        onClick={() => setDeleteId(doc.id)}
                        className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-red-400 hover:text-red-300 bg-red-400/5 hover:bg-red-400/10 rounded-lg border border-red-400/10 transition-all"
                      >
                        <Trash2 className="w-3.5 h-3.5" /> Excluir
                      </button>
                    </div>
                  </motion.div>
                )
              })}
            </AnimatePresence>
          </div>
        )}

        {/* Document List View */}
        {!loading && documents.length > 0 && viewMode === 'list' && (
          <div className="glass rounded-2xl overflow-hidden">
            <table className="w-full">
              <thead>
                <tr className="border-b border-white/10">
                  <th className="text-left px-5 py-3 text-xs font-medium text-gray-400 uppercase tracking-wider">Título</th>
                  <th className="text-left px-5 py-3 text-xs font-medium text-gray-400 uppercase tracking-wider hidden md:table-cell">Tipo</th>
                  <th className="text-left px-5 py-3 text-xs font-medium text-gray-400 uppercase tracking-wider hidden md:table-cell">Área</th>
                  <th className="text-left px-5 py-3 text-xs font-medium text-gray-400 uppercase tracking-wider hidden lg:table-cell">Palavras</th>
                  <th className="text-left px-5 py-3 text-xs font-medium text-gray-400 uppercase tracking-wider">Status</th>
                  <th className="text-left px-5 py-3 text-xs font-medium text-gray-400 uppercase tracking-wider hidden md:table-cell">Data</th>
                  <th className="px-5 py-3"></th>
                </tr>
              </thead>
              <tbody>
                <AnimatePresence mode="popLayout">
                  {documents.map((doc) => {
                    const status = STATUS_CONFIG[doc.status] || STATUS_CONFIG.COMPLETED
                    const StatusIcon = status.icon
                    return (
                      <motion.tr
                        key={doc.id}
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        onClick={() => router.push(`/dashboard/minhas-pecas/${doc.id}`)}
                        className="border-b border-white/5 hover:bg-white/[0.02] cursor-pointer transition-colors"
                      >
                        <td className="px-5 py-4">
                          <span className="text-white font-medium hover:text-teal-300 transition-colors">{doc.title}</span>
                        </td>
                        <td className="px-5 py-4 hidden md:table-cell">
                          <span className="px-2.5 py-1 text-xs font-medium text-teal-300 bg-teal-500/10 border border-teal-500/20 rounded-full">
                            {DOCUMENT_TYPES[doc.type] || doc.type}
                          </span>
                        </td>
                        <td className="px-5 py-4 hidden md:table-cell">
                          <span className="px-2.5 py-1 text-xs font-medium text-blue-300 bg-blue-500/10 border border-blue-500/20 rounded-full">
                            {AREAS[doc.area] || doc.area}
                          </span>
                        </td>
                        <td className="px-5 py-4 text-sm text-gray-400 hidden lg:table-cell">
                          {doc.wordCount.toLocaleString('pt-BR')}
                        </td>
                        <td className="px-5 py-4">
                          <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-full border ${status.color}`}>
                            <StatusIcon className="w-3 h-3" />
                            {status.label}
                          </span>
                        </td>
                        <td className="px-5 py-4 text-sm text-gray-400 hidden md:table-cell">{formatDate(doc.createdAt)}</td>
                        <td className="px-5 py-4" onClick={(e) => e.stopPropagation()}>
                          <div className="flex gap-1.5 justify-end">
                            <button onClick={() => handleCopy(doc.id)} className="p-2 text-gray-400 hover:text-white rounded-lg hover:bg-white/5 transition-all" title="Copiar">
                              <Copy className="w-4 h-4" />
                            </button>
                            <button onClick={() => setDeleteId(doc.id)} className="p-2 text-gray-400 hover:text-red-400 rounded-lg hover:bg-red-400/5 transition-all" title="Excluir">
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        </td>
                      </motion.tr>
                    )
                  })}
                </AnimatePresence>
              </tbody>
            </table>
          </div>
        )}
        </>
        )}
      </div>

      {/* Delete Confirmation Modal */}
      <AnimatePresence>
        {deleteId && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
            onClick={() => !deleting && setDeleteId(null)}
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              onClick={(e) => e.stopPropagation()}
              className="glass-strong rounded-2xl p-6 max-w-sm w-full"
            >
              <div className="flex items-center gap-3 mb-4">
                <div className="p-2 bg-red-400/10 rounded-xl">
                  <Trash2 className="w-6 h-6 text-red-400" />
                </div>
                <h3 className="text-lg font-semibold text-white">Excluir documento?</h3>
              </div>
              <p className="text-gray-400 text-sm mb-6">
                Esta ação não pode ser desfeita. O documento será removido permanentemente.
              </p>
              <div className="flex gap-3">
                <button
                  onClick={() => setDeleteId(null)}
                  disabled={deleting}
                  className="flex-1 py-2.5 text-sm font-medium text-gray-300 bg-white/5 hover:bg-white/10 border border-white/10 rounded-xl transition-all"
                >
                  Cancelar
                </button>
                <button
                  onClick={handleDelete}
                  disabled={deleting}
                  className="flex-1 py-2.5 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded-xl transition-all flex items-center justify-center gap-2"
                >
                  {deleting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
                  {deleting ? 'Excluindo...' : 'Excluir'}
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  )
}
