import { useEffect } from 'react'
import { Outlet, Link, useNavigate, useRouterState } from '@tanstack/react-router'
import { Loader2 } from 'lucide-react'
import { useAuth } from '@/auth/AuthContext'
import { AppHeader } from '@/components/AppHeader'
import { cn } from '@/lib/utils'

export function AdminLayout() {
  const { user, loading } = useAuth()
  const navigate = useNavigate()
  const pathname = useRouterState({ select: (s) => s.location.pathname })

  useEffect(() => {
    if (loading) return
    if (!user || user.platformRole !== 'platform_admin') {
      void navigate({ to: '/' })
    }
  }, [user, loading, navigate])

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin" style={{ color: '#F59845' }} />
      </div>
    )
  }

  if (!user || user.platformRole !== 'platform_admin') return null

  return (
    <div className="min-h-screen flex flex-col bg-slate-50">
      <AppHeader />
      <div className="flex-1 max-w-6xl mx-auto w-full px-6 py-8">
        <nav className="flex gap-1 border-b border-slate-200 mb-6">
          <AdminNavTab to="/admin/organizations" active={pathname.startsWith('/admin/organizations')}>
            Organizaciones
          </AdminNavTab>
          <AdminNavTab to="/admin/users" active={pathname.startsWith('/admin/users')}>
            Usuarios
          </AdminNavTab>
        </nav>
        <Outlet />
      </div>
    </div>
  )
}

function AdminNavTab({
  to,
  active,
  children,
}: {
  to: string
  active: boolean
  children: React.ReactNode
}) {
  return (
    <Link
      to={to}
      className={cn(
        'px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors',
        active
          ? 'border-[#F59845] text-[#F59845]'
          : 'border-transparent text-slate-600 hover:text-slate-900'
      )}
    >
      {children}
    </Link>
  )
}
