'use client'

import FileUpload from '@/components/FileUpload'
import { useState, useEffect } from 'react'
import {
  FileSearch,
  Plus,
  Loader2,
  AlertTriangle,
  CheckCircle2,
  XCircle,
  Clock,
  ArrowLeft,
  Shield,
  AlertOctagon,
  Search,
  Lightbulb,
  FileWarning,
  ThumbsUp,
  ChevronRight,
  Coins,
} from 'lucide-react'

interface AuditSummary {
  id: string
  title: string
  status: 'PENDING' | 'ANALYZING' | 'DONE' | 'ERROR'
  riskScore: number | null
  createdAt: string
}

interface AuditDetail {
  id: string
  title: string
  content: string
  status: string
  riskScore: number | null
  analysis: {
    resumo?: string
    riskScore?: number
    clausulasAbusivas?: { clausula: string; descricao: string; gravidade: string }[]
    inconsistencias?: { item: string; descricao: string }[]
    lacunas?: { item: string; descricao: string }[]
    riscos?: { risco: string; descricao: string; gravidade: string }[]
    sugestoes?: { sugestao: string; descricao: string }[]
    pontosFavoraveis?: { ponto: string; descricao: string }[]
  } | null
  createdAt: string
}

const statusLabels: Record<string, { label: string; color: string; icon: typeof Clock }> = {
  PENDING: { label: 'Pendente', color: 'text-zinc-400', icon: Clock },
  ANALYZING: { label: 'Analisando', color: 'text-yellow-400', icon: Loader2 },
  DONE: { label: 'Concluído', color: 'text-green-400', icon: CheckCircle2 },
  ERROR: { label: 'Erro', color: 'text-red-400', icon: XCircle },
}

function RiskGauge({ score }: { score: number }) {
  const getColor = (s: number) => {
    if (s <= 30) return { stroke: 'stroke-green-500', text: 'text-green-400', label: 'Baixo Risco' }
    if (s <= 60) return { stroke: 'stroke-yellow-500', text: 'text-yellow-400', label: 'Risco Moderado' }
    if (s <= 80) return { stroke: 'stroke-orange-500', text: 'text-orange-400', label: 'Risco Alto' }
    return { stroke: 'stroke-red-500', text: 'text-red-400', label: 'Risco Crítico' }
  }
  const config = getColor(score)
  const circumference = 2 * Math.PI * 45
  const dashOffset = circumference - (score / 100) * circumference

  return (
    <div className="flex flex-col items-center">
      <div className="relative h-32 w-32">
        <svg className="h-32 w-32 -rotate-90" viewBox="0 0 100 100">
          <circle cx="50" cy="50" r="45" fill="none" stroke="currentColor" strokeWidth="8" className="text-white/5" />
          <circle
            cx="50" cy="50" r="45" fill="none" strokeWidth="8" strokeLinecap="round"
            className={config.stroke}
            strokeDasharray={circumference}
            strokeDashoffset={dashOffset}
            style={{ transition: 'stroke-dashoffset 1s ease-in-out' }}
          />
        </svg>
        <div className="absolute inset-0 flex flex-col items-center justify-center">
          <span className={`text-3xl font-bold ${config.text}`}>{score}</span>
          <span className="text-[10px] text-zinc-500">/ 100</span>
        </div>
      </div>
      <p className={`mt-2 text-sm font-semibold ${config.text}`}>{config.label}</p>
    </div>
  )
}

export default function AuditoriaPage() {
  const [audits, setAudits] = useState<AuditSummary[]>([])
  const [loading, setLoading] = useState(true)
  const [view, setView] = useState<'list' | 'new' | 'detail'>('list')
  const [selectedAudit, setSelectedAudit] = useState<AuditDetail | null>(null)
  const [loadingDetail, setLoadingDetail] = useState(false)
  const [analyzing, setAnalyzing] = useState(false)
  const [error, setError] = useState('')

  // Form
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')

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

  async function fetchAudits() {
    setLoading(true)
    try {
      const res = await fetch('/api/auditoria')
      if (res.ok) {
        const data = await res.json()
        setAudits(data.audits || [])
      }
    } catch (e) {
      console.error('Failed to load audits:', e)
    } finally {
      setLoading(false)
    }
  }

  async function handleAnalyze() {
    if (!title.trim() || !content.trim()) return
    setAnalyzing(true)
    setError('')
    try {
      const res = await fetch('/api/auditoria', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title, content }),
      })
      const data = await res.json()
      if (!res.ok) {
        setError(data.error || 'Erro ao analisar')
        return
      }
      // Show result
      setSelectedAudit(data.audit)
      setView('detail')
      setTitle('')
      setContent('')
      fetchAudits()
    } catch (e) {
      setError('Erro de conexão')
    } finally {
      setAnalyzing(false)
    }
  }

  async function loadAuditDetail(id: string) {
    setLoadingDetail(true)
    try {
      const res = await fetch(`/api/auditoria/${id}`)
      if (res.ok) {
        const data = await res.json()
        setSelectedAudit(data.audit)
        setView('detail')
      }
    } catch (e) {
      console.error('Failed to load detail:', e)
    } finally {
      setLoadingDetail(false)
    }
  }

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

  function getRiskColor(score: number | null) {
    if (score === null) return 'text-zinc-500'
    if (score <= 30) return 'text-green-400'
    if (score <= 60) return 'text-yellow-400'
    if (score <= 80) return 'text-orange-400'
    return 'text-red-400'
  }

  // ─── Detail View ───
  if (view === 'detail' && selectedAudit) {
    const a = selectedAudit.analysis
    return (
      <div>
        <button
          onClick={() => { setView('list'); setSelectedAudit(null) }}
          className="mb-6 flex items-center gap-2 text-sm text-zinc-400 hover:text-teal-400"
        >
          <ArrowLeft className="h-4 w-4" />
          Voltar à lista
        </button>

        <div className="mb-6 flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-white">{selectedAudit.title}</h1>
            <p className="mt-1 text-sm text-zinc-500">Analisado em {formatDate(selectedAudit.createdAt)}</p>
          </div>
        </div>

        {a && (
          <div className="space-y-6">
            {/* Summary + Risk Score */}
            <div className="grid gap-6 md:grid-cols-[1fr,200px]">
              <div className="rounded-xl border border-white/5 bg-white/[0.02] p-6">
                <h3 className="text-sm font-semibold text-teal-400 mb-2">Resumo Executivo</h3>
                <p className="text-sm text-zinc-300 leading-relaxed">{a.resumo || 'Sem resumo disponível.'}</p>
              </div>
              <div className="flex items-center justify-center rounded-xl border border-white/5 bg-white/[0.02] p-4">
                <RiskGauge score={selectedAudit.riskScore || 0} />
              </div>
            </div>

            {/* Findings */}
            {a.clausulasAbusivas && a.clausulasAbusivas.length > 0 && (
              <FindingsSection
                title="Cláusulas Abusivas"
                icon={<AlertOctagon className="h-5 w-5 text-red-400" />}
                borderColor="border-red-500/20"
                items={a.clausulasAbusivas.map(c => ({
                  title: c.clausula,
                  desc: c.descricao,
                  badge: c.gravidade,
                }))}
              />
            )}

            {a.riscos && a.riscos.length > 0 && (
              <FindingsSection
                title="Riscos Identificados"
                icon={<AlertTriangle className="h-5 w-5 text-orange-400" />}
                borderColor="border-orange-500/20"
                items={a.riscos.map(r => ({
                  title: r.risco,
                  desc: r.descricao,
                  badge: r.gravidade,
                }))}
              />
            )}

            {a.inconsistencias && a.inconsistencias.length > 0 && (
              <FindingsSection
                title="Inconsistências"
                icon={<FileWarning className="h-5 w-5 text-yellow-400" />}
                borderColor="border-yellow-500/20"
                items={a.inconsistencias.map(i => ({ title: i.item, desc: i.descricao }))}
              />
            )}

            {a.lacunas && a.lacunas.length > 0 && (
              <FindingsSection
                title="Lacunas"
                icon={<Search className="h-5 w-5 text-blue-400" />}
                borderColor="border-blue-500/20"
                items={a.lacunas.map(l => ({ title: l.item, desc: l.descricao }))}
              />
            )}

            {a.sugestoes && a.sugestoes.length > 0 && (
              <FindingsSection
                title="Sugestões de Melhoria"
                icon={<Lightbulb className="h-5 w-5 text-teal-400" />}
                borderColor="border-teal-500/20"
                items={a.sugestoes.map(s => ({ title: s.sugestao, desc: s.descricao }))}
              />
            )}

            {a.pontosFavoraveis && a.pontosFavoraveis.length > 0 && (
              <FindingsSection
                title="Pontos Favoráveis"
                icon={<ThumbsUp className="h-5 w-5 text-green-400" />}
                borderColor="border-green-500/20"
                items={a.pontosFavoraveis.map(p => ({ title: p.ponto, desc: p.descricao }))}
              />
            )}
          </div>
        )}
      </div>
    )
  }

  // ─── New Audit View ───
  if (view === 'new') {
    return (
      <div>
        <button
          onClick={() => setView('list')}
          className="mb-6 flex items-center gap-2 text-sm text-zinc-400 hover:text-teal-400"
        >
          <ArrowLeft className="h-4 w-4" />
          Voltar à lista
        </button>

        <div className="mb-6">
          <h1 className="text-2xl font-bold text-white flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-teal-600/20">
              <FileSearch className="h-5 w-5 text-teal-400" />
            </div>
            Nova Auditoria de Contrato
          </h1>
          <p className="mt-1 text-sm text-zinc-500 flex items-center gap-2">
            <Coins className="h-4 w-4" />
            Custo: 3 créditos por análise
          </p>
        </div>

        <div className="space-y-4 max-w-3xl">
          <div>
            <label className="block text-sm font-medium text-zinc-400 mb-1">Título do Contrato *</label>
            <input
              type="text"
              value={title}
              onChange={e => setTitle(e.target.value)}
              className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-white outline-none focus:border-teal-500/40"
              placeholder="Ex: Contrato de Prestação de Serviços - Empresa X"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-zinc-400 mb-1">Texto do Contrato *</label>
            <textarea
              value={content}
              onChange={e => setContent(e.target.value)}
              className="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-white outline-none focus:border-teal-500/40 font-mono leading-relaxed"
              rows={16}
              placeholder="Cole aqui o texto completo do contrato para análise..."
            />
            <p className="mt-1 text-xs text-zinc-600">{content.length} caracteres {content.length < 100 && content.length > 0 ? '(mínimo 100)' : ''}</p>
          </div>

          <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
            <p className="text-sm font-medium text-zinc-400 mb-2">Ou faça upload do contrato</p>
            <FileUpload compact label="Upload de Contrato" maxFiles={1} />
            <p className="mt-2 text-xs text-zinc-600">O texto será extraído automaticamente do arquivo para análise.</p>
          </div>

          {error && (
            <div className="rounded-lg border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-400">
              {error}
            </div>
          )}

          <button
            onClick={handleAnalyze}
            disabled={!title.trim() || content.length < 100 || analyzing}
            className="flex items-center gap-2 rounded-xl bg-teal-600 px-6 py-3 text-sm font-semibold text-white transition-all hover:bg-teal-500 hover:shadow-lg hover:shadow-teal-500/20 disabled:opacity-50"
          >
            {analyzing ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" />
                Analisando contrato...
              </>
            ) : (
              <>
                <Shield className="h-4 w-4" />
                Analisar Contrato (3 créditos)
              </>
            )}
          </button>
        </div>
      </div>
    )
  }

  // ─── List View ───
  return (
    <div>
      <div className="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-teal-600/20">
              <FileSearch className="h-5 w-5 text-teal-400" />
            </div>
            Auditoria de Contratos
          </h1>
          <p className="mt-1 text-sm text-zinc-500">Análise inteligente de contratos com IA</p>
        </div>
        <button
          onClick={() => setView('new')}
          className="flex items-center gap-2 rounded-xl bg-teal-600 px-4 py-2.5 text-sm font-semibold text-white transition-all hover:bg-teal-500 hover:shadow-lg hover:shadow-teal-500/20"
        >
          <Plus className="h-4 w-4" />
          Nova Auditoria
        </button>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-16">
          <Loader2 className="h-6 w-6 animate-spin text-teal-400" />
        </div>
      ) : audits.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-xl border border-white/5 bg-white/[0.02] py-16">
          <FileSearch className="h-12 w-12 text-zinc-600" />
          <p className="mt-3 text-sm text-zinc-500">Nenhuma auditoria realizada</p>
          <button onClick={() => setView('new')} className="mt-4 text-sm text-teal-400 hover:text-teal-300">
            Fazer primeira auditoria
          </button>
        </div>
      ) : (
        <div className="space-y-3">
          {audits.map(audit => {
            const st = statusLabels[audit.status] || statusLabels.PENDING
            const StIcon = st.icon
            return (
              <button
                key={audit.id}
                onClick={() => loadAuditDetail(audit.id)}
                className="group flex w-full items-center gap-4 rounded-xl border border-white/5 bg-white/[0.02] p-4 text-left transition-all hover:bg-white/[0.04] hover:border-white/10"
              >
                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-teal-600/10 flex-shrink-0">
                  <FileSearch className="h-5 w-5 text-teal-400" />
                </div>
                <div className="flex-1 min-w-0">
                  <h3 className="font-semibold text-white truncate">{audit.title}</h3>
                  <p className="mt-0.5 text-xs text-zinc-500">{formatDate(audit.createdAt)}</p>
                </div>
                {audit.riskScore !== null && (
                  <div className={`text-lg font-bold ${getRiskColor(audit.riskScore)}`}>
                    {audit.riskScore}
                    <span className="text-xs font-normal text-zinc-600">/100</span>
                  </div>
                )}
                <span className={`flex items-center gap-1 text-xs font-medium ${st.color}`}>
                  <StIcon className={`h-3.5 w-3.5 ${audit.status === 'ANALYZING' ? 'animate-spin' : ''}`} />
                  {st.label}
                </span>
                <ChevronRight className="h-4 w-4 text-zinc-600 group-hover:text-zinc-400" />
              </button>
            )
          })}
        </div>
      )}

      {loadingDetail && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
          <div className="flex items-center gap-3 rounded-xl bg-[#0f1620] border border-white/10 px-6 py-4">
            <Loader2 className="h-5 w-5 animate-spin text-teal-400" />
            <span className="text-sm text-zinc-300">Carregando auditoria...</span>
          </div>
        </div>
      )}
    </div>
  )
}

// ─── Findings Section Component ───
function FindingsSection({ title, icon, borderColor, items }: {
  title: string
  icon: React.ReactNode
  borderColor: string
  items: { title: string; desc: string; badge?: string }[]
}) {
  const badgeColors: Record<string, string> = {
    alta: 'bg-red-500/15 text-red-400 border-red-500/30',
    media: 'bg-yellow-500/15 text-yellow-400 border-yellow-500/30',
    baixa: 'bg-green-500/15 text-green-400 border-green-500/30',
  }

  return (
    <div className={`rounded-xl border ${borderColor} bg-white/[0.02] p-6`}>
      <div className="flex items-center gap-2 mb-4">
        {icon}
        <h3 className="text-sm font-semibold text-white">{title}</h3>
        <span className="ml-auto rounded-full bg-white/5 px-2 py-0.5 text-[10px] font-bold text-zinc-400">
          {items.length}
        </span>
      </div>
      <div className="space-y-3">
        {items.map((item, i) => (
          <div key={i} className="rounded-lg border border-white/5 bg-white/[0.02] p-3">
            <div className="flex items-start justify-between gap-2">
              <h4 className="text-sm font-medium text-zinc-200">{item.title}</h4>
              {item.badge && (
                <span className={`rounded-md border px-2 py-0.5 text-[10px] font-bold uppercase flex-shrink-0 ${badgeColors[item.badge] || 'bg-zinc-500/15 text-zinc-400 border-zinc-500/30'}`}>
                  {item.badge}
                </span>
              )}
            </div>
            <p className="mt-1 text-xs text-zinc-400 leading-relaxed">{item.desc}</p>
          </div>
        ))}
      </div>
    </div>
  )
}
