'use client'

import { useState, useEffect, useRef, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import ReactMarkdown from 'react-markdown'
import {
  FileText,
  Upload,
  Brain,
  Scale,
  Loader2,
  Copy,
  Check,
  FileDown,
  Plus,
  Clock,
  AlertCircle,
  X,
  ChevronRight,
  Sparkles,
} from 'lucide-react'

interface AnalysisSummary {
  id: string
  title: string
  filename: string
  fileSize: number
  status: string
  summary: string | null
  createdAt: string
}

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('pt-BR', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

export default function AnaliseProcessoPage() {
  const router = useRouter()
  const [file, setFile] = useState<File | null>(null)
  const [dragOver, setDragOver] = useState(false)
  const [analyzing, setAnalyzing] = useState(false)
  const [analysis, setAnalysis] = useState('')
  const [analysisId, setAnalysisId] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [copied, setCopied] = useState(false)
  const [history, setHistory] = useState<AnalysisSummary[]>([])
  const [loadingHistory, setLoadingHistory] = useState(true)
  const [showHistory, setShowHistory] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const analysisRef = useRef<HTMLDivElement>(null)

  const fetchHistory = useCallback(async () => {
    try {
      const res = await fetch('/api/analise-processo')
      if (res.ok) {
        const data = await res.json()
        setHistory(data.analyses || [])
      }
    } catch {
      // ignore
    } finally {
      setLoadingHistory(false)
    }
  }, [])

  useEffect(() => {
    fetchHistory()
  }, [fetchHistory])

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(false)
    const dropped = e.dataTransfer.files[0]
    if (dropped?.type === 'application/pdf') {
      setFile(dropped)
      setError(null)
    } else {
      setError('Apenas arquivos PDF são aceitos.')
    }
  }, [])

  const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const selected = e.target.files?.[0]
    if (selected) {
      if (selected.type === 'application/pdf') {
        setFile(selected)
        setError(null)
      } else {
        setError('Apenas arquivos PDF são aceitos.')
      }
    }
  }, [])

  const handleAnalyze = async () => {
    if (!file) return
    setAnalyzing(true)
    setAnalysis('')
    setAnalysisId(null)
    setError(null)

    try {
      const formData = new FormData()
      formData.append('file', file)

      const res = await fetch('/api/analise-processo', {
        method: 'POST',
        body: formData,
      })

      if (!res.ok) {
        const data = await res.json()
        setError(data.error || 'Erro ao processar análise')
        setAnalyzing(false)
        return
      }

      const reader = res.body?.getReader()
      if (!reader) {
        setError('Erro na conexão com o servidor')
        setAnalyzing(false)
        return
      }

      const decoder = new TextDecoder()
      let buffer = ''

      while (true) {
        const { done, value } = await reader.read()
        if (done) break

        buffer += decoder.decode(value, { stream: true })
        const lines = buffer.split('\n\n')
        buffer = lines.pop() || ''

        for (const line of lines) {
          if (!line.startsWith('data: ')) continue
          try {
            const data = JSON.parse(line.slice(6))
            if (data.type === 'id') {
              setAnalysisId(data.id)
            } else if (data.type === 'chunk') {
              setAnalysis(prev => prev + data.content)
            } else if (data.type === 'done') {
              setAnalysisId(data.id)
              fetchHistory()
            } else if (data.type === 'error') {
              setError(data.message)
            }
          } catch {
            // ignore parse errors
          }
        }
      }
    } catch (err) {
      setError('Erro de conexão. Tente novamente.')
    } finally {
      setAnalyzing(false)
    }
  }

  const handleCopy = async () => {
    const plain = analysis.replace(/#{1,6}\s/g, '').replace(/\*\*/g, '').replace(/\*/g, '').replace(/- /g, '• ')
    await navigator.clipboard.writeText(plain)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  const handleExportDocx = async () => {
    const title = file?.name?.replace(/\.pdf$/i, '') || 'Análise de Processo'
    const res = await fetch('/api/export/docx', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title: `Análise - ${title}`, content: analysis }),
    })
    if (res.ok) {
      const blob = await res.blob()
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `analise-${title}.docx`
      a.click()
      URL.revokeObjectURL(url)
    }
  }

  const handleViewHistory = async (id: string) => {
    try {
      const res = await fetch(`/api/analise-processo/${id}`)
      if (res.ok) {
        const data = await res.json()
        setAnalysis(data.analysis.analysis)
        setAnalysisId(data.analysis.id)
        setFile(null)
        setShowHistory(false)
      }
    } catch {
      setError('Erro ao carregar análise')
    }
  }

  const handleReset = () => {
    setFile(null)
    setAnalysis('')
    setAnalysisId(null)
    setError(null)
    if (fileInputRef.current) fileInputRef.current.value = ''
  }

  const statusColors: Record<string, string> = {
    DONE: 'text-emerald-400',
    ANALYZING: 'text-amber-400',
    PENDING: 'text-zinc-400',
    ERROR: 'text-red-400',
  }

  const statusLabels: Record<string, string> = {
    DONE: 'Concluída',
    ANALYZING: 'Analisando...',
    PENDING: 'Pendente',
    ERROR: 'Erro',
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center 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">
              <Scale className="h-5 w-5 text-teal-400" />
            </div>
            Análise de Processo
          </h1>
          <p className="mt-1 text-sm text-zinc-400">
            Envie um PDF e receba uma análise jurídica completa com IA
          </p>
        </div>
        <button
          onClick={() => setShowHistory(!showHistory)}
          className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-zinc-300 transition hover:bg-white/10"
        >
          <Clock className="h-4 w-4" />
          Histórico
          {history.length > 0 && (
            <span className="rounded-full bg-teal-600/30 px-2 py-0.5 text-xs text-teal-400">
              {history.length}
            </span>
          )}
        </button>
      </div>

      <div className="flex gap-6">
        {/* Main Content */}
        <div className="flex-1 space-y-6">
          {/* Upload / Result */}
          {!analysis ? (
            <div className="rounded-2xl border border-white/5 bg-[#0d1420] p-6">
              {/* Drop Zone */}
              <div
                onDrop={handleDrop}
                onDragOver={e => { e.preventDefault(); setDragOver(true) }}
                onDragLeave={() => setDragOver(false)}
                onClick={() => fileInputRef.current?.click()}
                className={`relative cursor-pointer rounded-xl border-2 border-dashed p-12 text-center transition-all duration-200 ${
                  dragOver
                    ? 'border-teal-400 bg-teal-400/5'
                    : file
                    ? 'border-teal-500/30 bg-teal-500/5'
                    : 'border-white/10 hover:border-white/20 hover:bg-white/[0.02]'
                }`}
              >
                <input
                  ref={fileInputRef}
                  type="file"
                  accept=".pdf,application/pdf"
                  onChange={handleFileSelect}
                  className="hidden"
                />

                {file ? (
                  <div className="space-y-3">
                    <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-2xl bg-teal-600/20">
                      <FileText className="h-8 w-8 text-teal-400" />
                    </div>
                    <div>
                      <p className="text-lg font-medium text-white">{file.name}</p>
                      <p className="text-sm text-zinc-400">{formatFileSize(file.size)}</p>
                    </div>
                    <button
                      onClick={(e) => {
                        e.stopPropagation()
                        handleReset()
                      }}
                      className="inline-flex items-center gap-1 text-xs text-zinc-500 hover:text-zinc-300"
                    >
                      <X className="h-3 w-3" /> Remover
                    </button>
                  </div>
                ) : (
                  <div className="space-y-3">
                    <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-2xl bg-white/5">
                      <Upload className="h-8 w-8 text-zinc-500" />
                    </div>
                    <div>
                      <p className="text-lg font-medium text-zinc-300">
                        Arraste um PDF aqui ou clique para selecionar
                      </p>
                      <p className="text-sm text-zinc-500">
                        Processos judiciais, petições, contratos e outros documentos jurídicos
                      </p>
                    </div>
                  </div>
                )}
              </div>

              {/* Error */}
              {error && (
                <div className="mt-4 flex items-center gap-2 rounded-xl bg-red-500/10 border border-red-500/20 px-4 py-3 text-sm text-red-400">
                  <AlertCircle className="h-4 w-4 flex-shrink-0" />
                  {error}
                </div>
              )}

              {/* Analyze Button */}
              <div className="mt-6 flex items-center justify-between">
                <p className="flex items-center gap-1.5 text-xs text-zinc-500">
                  <Sparkles className="h-3 w-3 text-teal-500" />
                  A análise consome 5 créditos
                </p>
                <button
                  onClick={handleAnalyze}
                  disabled={!file || analyzing}
                  className="flex items-center gap-2 rounded-xl bg-teal-600 px-6 py-3 text-sm font-semibold text-white transition hover:bg-teal-500 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {analyzing ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" />
                      Analisando...
                    </>
                  ) : (
                    <>
                      <Brain className="h-4 w-4" />
                      Analisar Processo
                    </>
                  )}
                </button>
              </div>
            </div>
          ) : (
            <div className="space-y-4">
              {/* Action Bar */}
              <div className="flex items-center gap-3">
                <button
                  onClick={handleReset}
                  className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-zinc-300 transition hover:bg-white/10"
                >
                  <Plus className="h-4 w-4" />
                  Nova Análise
                </button>
                <button
                  onClick={handleCopy}
                  className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-zinc-300 transition hover:bg-white/10"
                >
                  {copied ? <Check className="h-4 w-4 text-emerald-400" /> : <Copy className="h-4 w-4" />}
                  {copied ? 'Copiado!' : 'Copiar'}
                </button>
                <button
                  onClick={handleExportDocx}
                  className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-zinc-300 transition hover:bg-white/10"
                >
                  <FileDown className="h-4 w-4" />
                  Baixar Word
                </button>
                {analysisId && !analyzing && (
                  <button
                    onClick={() => router.push(`/dashboard/nova-peca?from_analysis=${analysisId}`)}
                    className="flex items-center gap-2 rounded-xl bg-gradient-to-r from-teal-600 to-emerald-600 px-4 py-2 text-sm font-semibold text-white shadow-lg shadow-teal-500/20 transition hover:from-teal-500 hover:to-emerald-500"
                  >
                    <Sparkles className="h-4 w-4" />
                    Gerar Petição baseada neste Parecer
                  </button>
                )}
              </div>

              {/* Analysis Content */}
              <div
                ref={analysisRef}
                className="rounded-2xl border border-white/5 bg-[#0d1420] p-6 md:p-8"
              >
                {analyzing && (
                  <div className="mb-4 flex items-center gap-2 text-sm text-teal-400">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Analisando documento...
                  </div>
                )}
                <div className="prose prose-invert prose-teal max-w-none prose-headings:text-white prose-headings:border-b prose-headings:border-white/5 prose-headings:pb-2 prose-headings:mb-4 prose-h2:text-lg prose-h2:mt-8 prose-p:text-zinc-300 prose-li:text-zinc-300 prose-strong:text-teal-300 prose-ul:space-y-1">
                  <ReactMarkdown>{analysis}</ReactMarkdown>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* History Sidebar */}
        {showHistory && (
          <div className="hidden w-80 shrink-0 lg:block">
            <div className="sticky top-6 rounded-2xl border border-white/5 bg-[#0d1420] p-4">
              <h3 className="mb-4 flex items-center gap-2 text-sm font-semibold text-white">
                <Clock className="h-4 w-4 text-teal-400" />
                Análises Anteriores
              </h3>
              {loadingHistory ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 className="h-5 w-5 animate-spin text-zinc-500" />
                </div>
              ) : history.length === 0 ? (
                <p className="py-6 text-center text-sm text-zinc-500">
                  Nenhuma análise ainda
                </p>
              ) : (
                <div className="space-y-2 max-h-[60vh] overflow-y-auto">
                  {history.map((item) => (
                    <button
                      key={item.id}
                      onClick={() => handleViewHistory(item.id)}
                      className={`w-full rounded-xl p-3 text-left transition hover:bg-white/5 ${
                        analysisId === item.id ? 'bg-teal-600/10 border border-teal-500/20' : 'border border-transparent'
                      }`}
                    >
                      <div className="flex items-start justify-between gap-2">
                        <div className="min-w-0 flex-1">
                          <p className="truncate text-sm font-medium text-zinc-200">
                            {item.title}
                          </p>
                          <p className="mt-0.5 text-xs text-zinc-500">
                            {formatDate(item.createdAt)} • {formatFileSize(item.fileSize)}
                          </p>
                        </div>
                        <span className={`text-xs ${statusColors[item.status] || 'text-zinc-400'}`}>
                          {statusLabels[item.status] || item.status}
                        </span>
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Mobile History */}
      {showHistory && (
        <div className="lg:hidden rounded-2xl border border-white/5 bg-[#0d1420] p-4">
          <h3 className="mb-4 flex items-center gap-2 text-sm font-semibold text-white">
            <Clock className="h-4 w-4 text-teal-400" />
            Análises Anteriores
          </h3>
          {loadingHistory ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-5 w-5 animate-spin text-zinc-500" />
            </div>
          ) : history.length === 0 ? (
            <p className="py-6 text-center text-sm text-zinc-500">Nenhuma análise ainda</p>
          ) : (
            <div className="space-y-2">
              {history.map((item) => (
                <button
                  key={item.id}
                  onClick={() => handleViewHistory(item.id)}
                  className="flex w-full items-center justify-between rounded-xl border border-white/5 p-3 text-left transition hover:bg-white/5"
                >
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm font-medium text-zinc-200">{item.title}</p>
                    <p className="mt-0.5 text-xs text-zinc-500">
                      {formatDate(item.createdAt)} • {formatFileSize(item.fileSize)}
                    </p>
                  </div>
                  <ChevronRight className="h-4 w-4 flex-shrink-0 text-zinc-500" />
                </button>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  )
}
