import { getServerSession } from 'next-auth'
import { redirect } from 'next/navigation'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import Link from 'next/link'
import { Suspense } from 'react'
import { UpgradeSuccessBanner, UpgradePrompt } from './UpgradeBanner'
import {
  FileText,
  Coins,
  LetterText,
  Scale,
  FilePlus,
  ShieldAlert,
  MessageSquare,
  Search,
  TrendingUp,
  Clock,
  Sparkles,
} from 'lucide-react'

const typeLabels: 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 areaLabels: Record<string, string> = {
  CIVIL: 'Civil',
  TRABALHISTA: 'Trabalhista',
  PENAL: 'Penal',
  TRIBUTARIO: 'Tributário',
  FAMILIA: 'Família',
  EMPRESARIAL: 'Empresarial',
  CONSUMIDOR: 'Consumidor',
  ADMINISTRATIVO: 'Administrativo',
}

const areaColors: Record<string, string> = {
  CIVIL: 'bg-blue-500/15 text-blue-400',
  TRABALHISTA: 'bg-orange-500/15 text-orange-400',
  PENAL: 'bg-red-500/15 text-red-400',
  TRIBUTARIO: 'bg-green-500/15 text-green-400',
  FAMILIA: 'bg-pink-500/15 text-pink-400',
  EMPRESARIAL: 'bg-cyan-500/15 text-cyan-400',
  CONSUMIDOR: 'bg-yellow-500/15 text-yellow-400',
  ADMINISTRATIVO: 'bg-teal-500/15 text-teal-400',
}

const statusIndicator: Record<string, string> = {
  COMPLETED: 'bg-emerald-500',
  GENERATING: 'bg-amber-500 animate-pulse',
  ERROR: 'bg-red-500',
}

function formatDate(date: Date) {
  return new Intl.DateTimeFormat('pt-BR', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  }).format(date)
}

function formatNumber(n: number): string {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
  if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`
  return n.toLocaleString('pt-BR')
}

export default async function DashboardPage() {
  const session = await getServerSession(authOptions)
  if (!session?.user) redirect('/login')

  const userId = session.user.id

  // Fetch all stats in parallel
  const [
    documentCount,
    totalWords,
    jurisprudenciaCount,
    recentDocuments,
    user,
  ] = await Promise.all([
    prisma.document.count({ where: { userId } }),
    prisma.document.aggregate({
      where: { userId },
      _sum: { wordCount: true },
    }),
    prisma.usageLog.count({
      where: { userId, type: 'JURISPRUDENCIA' },
    }),
    prisma.document.findMany({
      where: { userId },
      orderBy: { createdAt: 'desc' },
      take: 10,
    }),
    prisma.user.findUnique({
      where: { id: userId },
      select: { credits: true, plan: true, name: true },
    }),
  ])

  const credits = user?.credits ?? 0
  const plan = user?.plan ?? 'FREE'
  const firstName = (user?.name ?? session.user.name).split(' ')[0]

  const stats = [
    {
      label: 'Peças criadas',
      value: formatNumber(documentCount),
      icon: FileText,
      color: 'from-teal-600 to-teal-800',
      iconBg: 'bg-teal-500/20',
      iconColor: 'text-teal-400',
    },
    {
      label: 'Créditos restantes',
      value: formatNumber(credits),
      icon: Coins,
      color: 'from-amber-600 to-amber-800',
      iconBg: 'bg-amber-500/20',
      iconColor: 'text-amber-400',
    },
    {
      label: 'Palavras geradas',
      value: formatNumber(totalWords._sum.wordCount ?? 0),
      icon: LetterText,
      color: 'from-cyan-600 to-cyan-800',
      iconBg: 'bg-cyan-500/20',
      iconColor: 'text-cyan-400',
    },
    {
      label: 'Jurisprudências consultadas',
      value: formatNumber(jurisprudenciaCount),
      icon: Scale,
      color: 'from-emerald-600 to-emerald-800',
      iconBg: 'bg-emerald-500/20',
      iconColor: 'text-emerald-400',
    },
  ]

  const quickActions = [
    {
      label: 'Nova Petição',
      href: '/dashboard/nova-peca?type=PETICAO_INICIAL',
      icon: FilePlus,
      desc: 'Petição inicial com IA',
      gradient: 'from-teal-600 to-indigo-700',
    },
    {
      label: 'Nova Contestação',
      href: '/dashboard/nova-peca?type=CONTESTACAO',
      icon: ShieldAlert,
      desc: 'Contestação fundamentada',
      gradient: 'from-rose-600 to-pink-700',
    },
    {
      label: 'Chat IA',
      href: '/dashboard/chat',
      icon: MessageSquare,
      desc: 'Tire dúvidas com IA',
      gradient: 'from-cyan-600 to-teal-700',
    },
    {
      label: 'Buscar Jurisprudência',
      href: '/dashboard/jurisprudencia',
      icon: Search,
      desc: 'Pesquise decisões',
      gradient: 'from-amber-600 to-orange-700',
    },
  ]

  const greeting = (() => {
    const h = new Date().getHours()
    if (h < 12) return 'Bom dia'
    if (h < 18) return 'Boa tarde'
    return 'Boa noite'
  })()

  const planBadge: Record<string, { label: string; style: string }> = {
    FREE: { label: 'Free', style: 'bg-zinc-700 text-zinc-300' },
    STARTER: { label: 'Starter', style: 'bg-blue-600/20 text-blue-400 border border-blue-500/30' },
    PRO: { label: 'Pro', style: 'bg-teal-600/20 text-teal-400 border border-teal-500/30' },
    ENTERPRISE: { label: 'Enterprise', style: 'bg-amber-600/20 text-amber-400 border border-amber-500/30' },
  }

  const badge = planBadge[plan] || planBadge.FREE

  return (
    <div className="space-y-8">
      <Suspense fallback={null}>
        <UpgradeSuccessBanner />
      </Suspense>
      <UpgradePrompt plan={plan} credits={credits} />
      {/* Welcome card */}
      <div className="relative overflow-hidden rounded-2xl border border-white/5 bg-gradient-to-br from-teal-900/30 via-[#111b27] to-[#0f1620] p-6 sm:p-8">
        <div className="absolute -right-20 -top-20 h-60 w-60 rounded-full bg-teal-600/10 blur-3xl" />
        <div className="absolute -bottom-10 -left-10 h-40 w-40 rounded-full bg-indigo-600/10 blur-3xl" />
        <div className="relative">
          <div className="flex flex-wrap items-center gap-3">
            <h1 className="text-2xl font-bold text-white sm:text-3xl">
              {greeting}, {firstName}! <span className="inline-block animate-[wave_2s_ease-in-out_infinite]">👋</span>
            </h1>
            <span
              className={`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-bold uppercase tracking-wider ${badge.style}`}
            >
              <Sparkles className="h-3 w-3" />
              {badge.label}
            </span>
          </div>
          <p className="mt-2 max-w-xl text-sm text-zinc-400 sm:text-base">
            Aqui está um resumo da sua atividade. Crie peças jurídicas com IA, pesquise jurisprudência e muito mais.
          </p>
        </div>
      </div>

      {/* Stat cards */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {stats.map((stat) => {
          const Icon = stat.icon
          return (
            <div
              key={stat.label}
              className="group relative overflow-hidden rounded-2xl border border-white/5 bg-[#111b27] p-5 transition-all duration-200 hover:border-white/10 hover:bg-[#162030]"
            >
              <div className="flex items-center justify-between">
                <div className={`rounded-xl p-2.5 ${stat.iconBg}`}>
                  <Icon className={`h-5 w-5 ${stat.iconColor}`} />
                </div>
                <TrendingUp className="h-4 w-4 text-zinc-600 transition-colors group-hover:text-zinc-400" />
              </div>
              <p className="mt-4 text-2xl font-bold tracking-tight text-white">
                {stat.value}
              </p>
              <p className="mt-0.5 text-sm text-zinc-500">{stat.label}</p>
            </div>
          )
        })}
      </div>

      {/* Quick actions */}
      <div>
        <h2 className="mb-4 text-lg font-semibold text-white">Ações rápidas</h2>
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
          {quickActions.map((action) => {
            const Icon = action.icon
            return (
              <Link
                key={action.label}
                href={action.href}
                className="group relative overflow-hidden rounded-2xl border border-white/5 bg-[#111b27] p-5 transition-all duration-200 hover:border-teal-500/20 hover:shadow-lg hover:shadow-teal-900/10"
              >
                <div
                  className={`inline-flex rounded-xl bg-gradient-to-br ${action.gradient} p-2.5`}
                >
                  <Icon className="h-5 w-5 text-white" />
                </div>
                <h3 className="mt-3 text-sm font-semibold text-white group-hover:text-teal-300">
                  {action.label}
                </h3>
                <p className="mt-0.5 text-xs text-zinc-500">{action.desc}</p>
              </Link>
            )
          })}
        </div>
      </div>

      {/* Recent documents */}
      <div>
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-lg font-semibold text-white">Documentos recentes</h2>
          <Link
            href="/dashboard/minhas-pecas"
            className="text-sm text-teal-400 transition-colors hover:text-teal-300"
          >
            Ver todos →
          </Link>
        </div>

        {recentDocuments.length === 0 ? (
          <div className="flex flex-col items-center justify-center rounded-2xl border border-dashed border-white/10 bg-[#111b27] py-16 text-center">
            <FileText className="h-12 w-12 text-zinc-700" />
            <h3 className="mt-4 text-base font-medium text-zinc-400">
              Nenhum documento ainda
            </h3>
            <p className="mt-1 text-sm text-zinc-600">
              Crie sua primeira peça jurídica com IA
            </p>
            <Link
              href="/dashboard/nova-peca"
              className="mt-5 inline-flex items-center gap-2 rounded-xl bg-teal-600 px-5 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-teal-500"
            >
              <FilePlus className="h-4 w-4" />
              Nova Peça
            </Link>
          </div>
        ) : (
          <div className="overflow-hidden rounded-2xl border border-white/5 bg-[#111b27]">
            {/* Desktop table */}
            <div className="hidden sm:block">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-white/5 text-left text-xs font-medium uppercase tracking-wider text-zinc-500">
                    <th className="px-5 py-3.5">Título</th>
                    <th className="px-5 py-3.5">Tipo</th>
                    <th className="px-5 py-3.5">Área</th>
                    <th className="px-5 py-3.5">Palavras</th>
                    <th className="px-5 py-3.5">Status</th>
                    <th className="px-5 py-3.5">Data</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/5">
                  {recentDocuments.map((doc) => (
                    <tr
                      key={doc.id}
                      className="transition-colors hover:bg-white/[0.02]"
                    >
                      <td className="px-5 py-3.5">
                        <Link
                          href={`/dashboard/minhas-pecas/${doc.id}`}
                          className="text-sm font-medium text-white hover:text-teal-400"
                        >
                          {doc.title}
                        </Link>
                      </td>
                      <td className="px-5 py-3.5">
                        <span className="text-sm text-zinc-400">
                          {typeLabels[doc.type] || doc.type}
                        </span>
                      </td>
                      <td className="px-5 py-3.5">
                        <span
                          className={`inline-block rounded-md px-2 py-0.5 text-xs font-medium ${
                            areaColors[doc.area] || 'bg-zinc-700 text-zinc-400'
                          }`}
                        >
                          {areaLabels[doc.area] || doc.area}
                        </span>
                      </td>
                      <td className="px-5 py-3.5 text-sm text-zinc-400">
                        {doc.wordCount.toLocaleString('pt-BR')}
                      </td>
                      <td className="px-5 py-3.5">
                        <div className="flex items-center gap-2">
                          <span
                            className={`h-2 w-2 rounded-full ${
                              statusIndicator[doc.status] || 'bg-zinc-500'
                            }`}
                          />
                          <span className="text-xs text-zinc-400">
                            {doc.status === 'COMPLETED'
                              ? 'Concluído'
                              : doc.status === 'GENERATING'
                                ? 'Gerando...'
                                : 'Erro'}
                          </span>
                        </div>
                      </td>
                      <td className="px-5 py-3.5">
                        <div className="flex items-center gap-1.5 text-xs text-zinc-500">
                          <Clock className="h-3.5 w-3.5" />
                          {formatDate(doc.createdAt)}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Mobile cards */}
            <div className="divide-y divide-white/5 sm:hidden">
              {recentDocuments.map((doc) => (
                <Link
                  key={doc.id}
                  href={`/dashboard/minhas-pecas/${doc.id}`}
                  className="block p-4 transition-colors hover:bg-white/[0.02]"
                >
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0 flex-1">
                      <p className="truncate text-sm font-medium text-white">
                        {doc.title}
                      </p>
                      <p className="mt-0.5 text-xs text-zinc-500">
                        {typeLabels[doc.type] || doc.type} · {doc.wordCount.toLocaleString('pt-BR')} palavras
                      </p>
                    </div>
                    <span
                      className={`mt-0.5 h-2 w-2 flex-shrink-0 rounded-full ${
                        statusIndicator[doc.status] || 'bg-zinc-500'
                      }`}
                    />
                  </div>
                  <div className="mt-2 flex items-center gap-2">
                    <span
                      className={`rounded-md px-2 py-0.5 text-[10px] font-medium ${
                        areaColors[doc.area] || 'bg-zinc-700 text-zinc-400'
                      }`}
                    >
                      {areaLabels[doc.area] || doc.area}
                    </span>
                    <span className="text-[10px] text-zinc-600">
                      {formatDate(doc.createdAt)}
                    </span>
                  </div>
                </Link>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
