'use client'

import { usePathname } from 'next/navigation'
import Link from 'next/link'
import { useState } from 'react'
import {
  LayoutDashboard,
  FilePlus,
  FileText,
  MessageSquare,
  Brain,
  Clock,
  FileSearch,
  Scale,
  BookTemplate,
  Settings,
  Menu,
  X,
  LogOut,
  ChevronRight,
  Sparkles,
  Newspaper,
} from 'lucide-react'
import { signOut } from 'next-auth/react'

interface DashboardShellProps {
  children: React.ReactNode
  user: {
    name: string
    email: string
    plan: string
    avatar?: string | null
    oabNumber?: string | null
    oabState?: string | null
  }
}

const navItems = [
  { href: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
  { href: '/dashboard/nova-peca', label: 'Novo Documento', icon: FilePlus },
  { href: '/dashboard/minhas-pecas', label: 'Meus Documentos', icon: FileText },
  { href: '/dashboard/chat', label: 'Consultor IA', icon: MessageSquare },
  { href: '/dashboard/jurisprudencia', label: 'Jurisprudência', icon: Brain },
  { href: '/dashboard/prazos', label: 'Gestão de Prazos', icon: Clock },
  { href: '/dashboard/publicacoes', label: 'Publicações', icon: Newspaper },
  { href: '/dashboard/auditoria', label: 'Auditoria Contratos', icon: FileSearch },
  { href: '/dashboard/analise-processo', label: 'Análise de Processo', icon: Scale },
  { href: '/dashboard/modelos', label: 'Modelos', icon: BookTemplate },
  { href: '/dashboard/configuracoes', label: 'Configurações', icon: Settings },
]

const planColors: Record<string, string> = {
  FREE: 'bg-zinc-700 text-zinc-300',
  PRO: 'bg-teal-600/20 text-teal-400 border border-teal-500/30',
  ENTERPRISE: 'bg-amber-600/20 text-amber-400 border border-amber-500/30',
}

const planLabels: Record<string, string> = {
  FREE: 'Free',
  PRO: 'Pro',
  ENTERPRISE: 'Enterprise',
}

export default function DashboardShell({ children, user }: DashboardShellProps) {
  const pathname = usePathname()
  const [sidebarOpen, setSidebarOpen] = useState(false)

  const isActive = (href: string) => {
    if (href === '/dashboard') return pathname === '/dashboard'
    return pathname.startsWith(href)
  }

  const initials = user.name
    .split(' ')
    .map((n) => n[0])
    .slice(0, 2)
    .join('')
    .toUpperCase()

  return (
    <div className="flex h-screen overflow-hidden bg-[#0f1620]">
      {/* Mobile overlay */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 z-40 bg-black/60 backdrop-blur-sm lg:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}

      {/* Sidebar */}
      <aside
        className={`
          fixed inset-y-0 left-0 z-50 flex w-72 flex-col border-r border-white/5 bg-[#0a1018]
          transition-transform duration-300 ease-in-out lg:static lg:translate-x-0
          ${sidebarOpen ? 'translate-x-0' : '-translate-x-full'}
        `}
      >
        {/* Logo */}
        <div className="flex h-16 items-center gap-3 border-b border-white/5 px-6">
          <div className="relative flex h-9 w-9 items-center justify-center rounded-lg bg-gradient-to-br from-teal-600 via-teal-500 to-cyan-500">
            <Brain className="h-5 w-5 text-white" />
            <div className="absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full bg-gradient-to-br from-cyan-400 to-teal-600 flex items-center justify-center">
              <span className="text-[6px] font-bold text-white">§</span>
            </div>
          </div>
          <div>
            <span className="text-lg font-bold text-white">Lex</span>
            <span className="text-lg font-bold text-teal-400">Mind</span>
          </div>
          <button
            onClick={() => setSidebarOpen(false)}
            className="ml-auto rounded-lg p-1.5 text-zinc-400 hover:bg-white/5 hover:text-white lg:hidden"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Navigation */}
        <nav className="flex-1 overflow-y-auto px-3 py-4">
          <div className="space-y-1">
            {navItems.map((item) => {
              const active = isActive(item.href)
              const Icon = item.icon
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  onClick={() => setSidebarOpen(false)}
                  className={`
                    group flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium
                    transition-all duration-150
                    ${
                      active
                        ? 'bg-teal-600/15 text-teal-400 shadow-[inset_0_0_0_1px_rgba(139,92,246,0.2)]'
                        : 'text-zinc-400 hover:bg-white/5 hover:text-zinc-200'
                    }
                  `}
                >
                  <Icon
                    className={`h-5 w-5 flex-shrink-0 ${
                      active ? 'text-teal-400' : 'text-zinc-500 group-hover:text-zinc-300'
                    }`}
                  />
                  {item.label}
                  {active && (
                    <ChevronRight className="ml-auto h-4 w-4 text-teal-500/60" />
                  )}
                </Link>
              )
            })}
          </div>

          {/* Upgrade CTA for free users */}
          {user.plan === 'FREE' && (
            <div className="mx-1 mt-6 rounded-xl border border-teal-500/20 bg-gradient-to-br from-teal-600/10 to-teal-900/10 p-4">
              <div className="flex items-center gap-2 text-sm font-semibold text-teal-300">
                <Sparkles className="h-4 w-4" />
                Ativar plano Advocacia
              </div>
              <p className="mt-1.5 text-xs leading-relaxed text-zinc-400">
                Documentos ilimitados, consultor avançado e jurisprudência premium.
              </p>
              <Link
                href="/dashboard/configuracoes#planos"
                className="mt-3 block rounded-lg bg-teal-600 px-3 py-1.5 text-center text-xs font-semibold text-white transition-colors hover:bg-teal-500"
              >
                Ver opções
              </Link>
            </div>
          )}
        </nav>

        {/* User info */}
        <div className="border-t border-white/5 p-3">
          <div className="flex items-center gap-3 rounded-xl px-3 py-3">
            {user.avatar ? (
              <img
                src={user.avatar}
                alt={user.name}
                className="h-9 w-9 rounded-full object-cover ring-2 ring-teal-500/30"
              />
            ) : (
              <div className="flex h-9 w-9 items-center justify-center rounded-full bg-teal-600/20 text-sm font-bold text-teal-400 ring-2 ring-teal-500/30">
                {initials}
              </div>
            )}
            <div className="flex-1 overflow-hidden">
              <p className="truncate text-sm font-medium text-white">{user.name}</p>
              <div className="flex items-center gap-2">
                <p className="truncate text-xs text-zinc-500">{user.email}</p>
              </div>
            </div>
            <span
              className={`rounded-md px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide ${
                planColors[user.plan] || planColors.FREE
              }`}
            >
              {planLabels[user.plan] || user.plan}
            </span>
          </div>
          <button
            onClick={() => signOut({ callbackUrl: '/login' })}
            className="mt-1 flex w-full items-center gap-2 rounded-xl px-3 py-2 text-sm text-zinc-500 transition-colors hover:bg-red-500/10 hover:text-red-400"
          >
            <LogOut className="h-4 w-4" />
            Sair
          </button>
        </div>
      </aside>

      {/* Main content */}
      <div className="flex flex-1 flex-col overflow-hidden">
        {/* Top bar (mobile) */}
        <header className="flex h-14 items-center gap-3 border-b border-white/5 bg-[#0a1018]/80 px-4 backdrop-blur-md lg:hidden">
          <button
            onClick={() => setSidebarOpen(true)}
            className="rounded-lg p-2 text-zinc-400 hover:bg-white/5 hover:text-white"
          >
            <Menu className="h-5 w-5" />
          </button>
          <div className="flex items-center gap-2">
            <div className="relative flex h-7 w-7 items-center justify-center rounded-md bg-gradient-to-br from-teal-500 via-teal-500 to-cyan-500">
              <Brain className="h-4 w-4 text-white" />
            </div>
            <span className="text-sm font-bold text-white">Lex</span>
            <span className="text-sm font-bold text-teal-400">Mind</span>
          </div>
        </header>

        {/* Page content */}
        <main className="flex-1 overflow-y-auto">
          <div className="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
            {children}
          </div>
        </main>
      </div>
    </div>
  )
}
