'use client'

import { useState, useEffect, use } from 'react'
import { useRouter } from 'next/navigation'
import { motion } from 'framer-motion'
import ReactMarkdown from 'react-markdown'
import { stripMarkdown, downloadAsWord } from '@/lib/utils'
import {
  ArrowLeft, Copy, Printer, RefreshCw, FileText, Calendar,
  Hash, DollarSign, Tag, Briefcase, CheckCircle2, Clock,
  AlertTriangle, Loader2, FileDown
} from 'lucide-react'

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
  content: string
  prompt: string
  wordCount: number
  tokens: number
  cost: number
  createdAt: string
}

export default function DocumentViewerPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params)
  const router = useRouter()
  const [doc, setDoc] = useState<Document | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [copied, setCopied] = useState(false)
  const [downloadingWord, setDownloadingWord] = useState(false)

  useEffect(() => {
    fetch(`/api/documents/${id}`)
      .then(res => {
        if (!res.ok) throw new Error('Documento não encontrado')
        return res.json()
      })
      .then(data => setDoc(data.document))
      .catch(err => setError(err.message))
      .finally(() => setLoading(false))
  }, [id])

  const handleCopy = async () => {
    if (!doc) return
    await navigator.clipboard.writeText(stripMarkdown(doc.content))
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  const handlePrint = () => {
    window.print()
  }

  const handleDownloadWord = async () => {
    if (!doc) return
    setDownloadingWord(true)
    try {
      await downloadAsWord(doc.title, doc.content)
    } catch (err) {
      console.error('Word download error:', err)
    } finally {
      setDownloadingWord(false)
    }
  }

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

  if (loading) {
    return (
      <div className="min-h-screen bg-[#0a0f1a] flex items-center justify-center">
        <Loader2 className="w-8 h-8 text-teal-400 animate-spin" />
      </div>
    )
  }

  if (error || !doc) {
    return (
      <div className="min-h-screen bg-[#0a0f1a] flex flex-col items-center justify-center gap-4">
        <AlertTriangle className="w-12 h-12 text-red-400" />
        <h2 className="text-xl font-semibold text-white">{error || 'Documento não encontrado'}</h2>
        <button
          onClick={() => router.push('/dashboard/minhas-pecas')}
          className="flex items-center gap-2 px-4 py-2 text-teal-400 hover:text-teal-300 transition-colors"
        >
          <ArrowLeft className="w-4 h-4" /> Voltar para Minhas Peças
        </button>
      </div>
    )
  }

  const status = STATUS_CONFIG[doc.status] || STATUS_CONFIG.COMPLETED
  const StatusIcon = status.icon

  return (
    <div className="min-h-screen bg-[#0a0f1a] p-4 md:p-8">
      <div className="max-w-5xl mx-auto">
        {/* Top Bar */}
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-6"
        >
          <button
            onClick={() => router.push('/dashboard/minhas-pecas')}
            className="flex items-center gap-2 text-gray-400 hover:text-white transition-colors w-fit"
          >
            <ArrowLeft className="w-5 h-5" />
            Voltar para Minhas Peças
          </button>

          <div className="flex gap-2 print:hidden">
            <button
              onClick={handleCopy}
              className="flex items-center gap-2 px-4 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"
            >
              <Copy className="w-4 h-4" />
              {copied ? 'Copiado!' : 'Copiar'}
            </button>
            <button
              onClick={handlePrint}
              className="flex items-center gap-2 px-4 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"
            >
              <Printer className="w-4 h-4" />
              Imprimir
            </button>
            <button
              onClick={handleDownloadWord}
              disabled={downloadingWord}
              className="flex items-center gap-2 px-4 py-2.5 text-sm font-medium text-white bg-teal-600 hover:bg-teal-500 border border-teal-500/30 rounded-xl transition-all"
            >
              <FileDown className="w-4 h-4" />
              {downloadingWord ? 'Gerando...' : 'Baixar Word'}
            </button>
            <button
              onClick={() => router.push('/dashboard/gerar')}
              className="flex items-center gap-2 px-4 py-2.5 text-sm font-medium text-white bg-teal-600 hover:bg-teal-700 rounded-xl transition-all glow-purple"
            >
              <RefreshCw className="w-4 h-4" />
              Gerar Nova Versão
            </button>
          </div>
        </motion.div>

        {/* Document Header */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="glass rounded-2xl p-6 mb-6"
        >
          <div className="flex flex-wrap items-center gap-3 mb-4">
            <span className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-full border ${status.color}`}>
              <StatusIcon className="w-3.5 h-3.5" />
              {status.label}
            </span>
            <span className="px-3 py-1.5 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-3 py-1.5 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>

          <h1 className="text-2xl md:text-3xl font-bold text-white mb-4">{doc.title}</h1>

          {/* Metadata Grid */}
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
            <div className="flex items-center gap-2">
              <Calendar className="w-4 h-4 text-gray-500" />
              <div>
                <p className="text-xs text-gray-500">Data</p>
                <p className="text-sm text-gray-300">{formatDate(doc.createdAt)}</p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <FileText className="w-4 h-4 text-gray-500" />
              <div>
                <p className="text-xs text-gray-500">Palavras</p>
                <p className="text-sm text-gray-300">{doc.wordCount.toLocaleString('pt-BR')}</p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Hash className="w-4 h-4 text-gray-500" />
              <div>
                <p className="text-xs text-gray-500">Tokens</p>
                <p className="text-sm text-gray-300">{doc.tokens.toLocaleString('pt-BR')}</p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <DollarSign className="w-4 h-4 text-gray-500" />
              <div>
                <p className="text-xs text-gray-500">Custo</p>
                <p className="text-sm text-gray-300">R$ {doc.cost.toFixed(4)}</p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Tag className="w-4 h-4 text-gray-500" />
              <div>
                <p className="text-xs text-gray-500">Tipo</p>
                <p className="text-sm text-gray-300">{DOCUMENT_TYPES[doc.type] || doc.type}</p>
              </div>
            </div>
          </div>
        </motion.div>

        {/* Prompt (collapsed) */}
        {doc.prompt && (
          <motion.details
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.15 }}
            className="glass rounded-2xl mb-6 print:hidden"
          >
            <summary className="px-6 py-4 cursor-pointer text-gray-400 hover:text-gray-300 transition-colors flex items-center gap-2">
              <Briefcase className="w-4 h-4" />
              <span className="text-sm font-medium">Prompt utilizado</span>
            </summary>
            <div className="px-6 pb-5 text-sm text-gray-400 whitespace-pre-wrap border-t border-white/5 pt-4">
              {doc.prompt}
            </div>
          </motion.details>
        )}

        {/* Document Content */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="glass rounded-2xl p-6 md:p-10"
        >
          <div className="prose prose-invert prose-purple max-w-none
            prose-headings:text-white prose-headings:font-bold
            prose-h1:text-2xl prose-h2:text-xl prose-h3:text-lg
            prose-p:text-gray-300 prose-p:leading-relaxed
            prose-strong:text-white
            prose-a:text-teal-400 prose-a:no-underline hover:prose-a:underline
            prose-blockquote:border-teal-500/40 prose-blockquote:bg-teal-500/5 prose-blockquote:rounded-r-lg prose-blockquote:py-1
            prose-code:text-teal-300 prose-code:bg-teal-500/10 prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded
            prose-li:text-gray-300
            prose-hr:border-white/10
          ">
            <ReactMarkdown>{doc.content}</ReactMarkdown>
          </div>
        </motion.div>
      </div>
    </div>
  )
}
