import { createFileRoute, Link, Outlet, redirect, useRouter, useRouterState } from '@tanstack/react-router'
import { logout } from '@netlify/identity'
import {
  BadgeCheck,
  CalendarDays,
  CreditCard,
  ExternalLink,
  KeyRound,
  LayoutDashboard,
  LogOut,
  MessageCircle,
  MessageSquareText,
  ShieldCheck,
  Users,
} from 'lucide-react'
import { toast } from 'sonner'
import { Avatar } from '@/components/admin/AdminUi'
import { Logo } from '@/components/Logo'
import { getAdminNavCounts } from '@/lib/admin.functions'
import { getServerUser } from '@/lib/identity.functions'
import { cn } from '@/lib/utils'

// Layout for every /admin page. It is a standalone console, separate from the public
// website. The guard here covers the pages, and each admin server function checks
// the role again with `requireAdmin`.
export const Route = createFileRoute('/admin')({
  head: () => ({ meta: [{ title: 'Admin — AkotoCreative SMS' }, { name: 'robots', content: 'noindex, nofollow' }] }),
  beforeLoad: async () => {
    const user = await getServerUser()
    if (!user || !user.isAdmin) throw redirect({ to: '/admin/login' })
    return { adminUser: user }
  },
  loader: () => getAdminNavCounts(),
  component: AdminLayout,
})

const NAV = [
  { to: '/admin', label: 'Overview', icon: LayoutDashboard, exact: true },
  { to: '/admin/customers', label: 'Customers', icon: Users },
  { to: '/admin/payments', label: 'Payments', icon: CreditCard, count: 'payments' },
  { to: '/admin/messages', label: 'Messages', icon: MessageSquareText },
  { to: '/admin/chat', label: 'Chat with us', icon: MessageCircle, count: 'chat' },
  { to: '/admin/sender-ids', label: 'Sender IDs', icon: BadgeCheck, count: 'senderIds' },
  { to: '/admin/settings', label: 'API settings', icon: KeyRound },
] as const

const linkClass =
  'group relative flex items-center gap-3 whitespace-nowrap rounded-xl px-3 py-2.5 text-sm font-medium text-white/65 transition-all hover:bg-white/[0.06] hover:text-white'
const activeClass =
  'bg-gradient-to-r from-white/[0.14] to-white/[0.03] text-white shadow-[inset_0_1px_0_rgb(255_255_255/0.08)] before:absolute before:inset-y-2 before:-left-3 before:hidden before:w-1 before:rounded-r-full before:bg-[var(--gold-glow)] lg:before:block'

const todayFormat = new Intl.DateTimeFormat('en-GH', { weekday: 'long', day: 'numeric', month: 'long' })

function AdminLayout() {
  const { adminUser } = Route.useRouteContext()
  const counts = Route.useLoaderData()
  const router = useRouter()
  const pathname = useRouterState({ select: (s) => s.location.pathname })
  const current = [...NAV].reverse().find((item) => pathname.startsWith(item.to)) ?? NAV[0]

  async function handleLogout() {
    try {
      await logout()
      await router.invalidate()
      await router.navigate({ to: '/admin/login' })
    } catch {
      toast.error('We could not sign you out. Please try again.')
    }
  }

  const navLinks = NAV.map((item) => {
    const count = 'count' in item ? counts[item.count] : 0
    return (
      <li key={item.to}>
        <Link
          to={item.to}
          activeOptions={{ exact: 'exact' in item, includeSearch: false }}
          className={linkClass}
          activeProps={{ className: activeClass }}
        >
          {({ isActive }) => (
            <>
              <span
                className={cn(
                  'grid size-7 place-items-center rounded-lg transition-colors',
                  isActive
                    ? 'bg-[var(--gold-glow)] text-[var(--forest-950)] shadow-[0_6px_18px_-6px_var(--gold-glow)]'
                    : 'bg-white/[0.06] text-white/70 group-hover:text-white',
                )}
              >
                <item.icon className="size-4" aria-hidden />
              </span>
              <span className="flex-1">{item.label}</span>
              {count > 0 && (
                <span className="rounded-full bg-[var(--gold-glow)]/20 px-2 py-0.5 text-[0.7rem] font-bold text-[var(--gold-glow)] tabular-nums ring-1 ring-[var(--gold-glow)]/30 ring-inset">
                  {count.toLocaleString()}
                  <span className="sr-only"> waiting</span>
                </span>
              )}
            </>
          )}
        </Link>
      </li>
    )
  })

  return (
    <div className="min-h-screen bg-[radial-gradient(90rem_40rem_at_100%_-10%,color-mix(in_oklch,var(--gold-glow)_10%,transparent),transparent),radial-gradient(60rem_30rem_at_0%_110%,color-mix(in_oklch,var(--primary)_8%,transparent),transparent)] bg-background lg:grid lg:grid-cols-[17rem_1fr]">
      <aside className="stage grain sticky top-0 z-40 overflow-hidden border-b border-white/10 lg:h-screen lg:border-r lg:border-b-0">
        <div className="aurora opacity-50" aria-hidden />
        <div className="relative z-10 flex h-full flex-col">
          <div className="flex h-16 items-center gap-3 px-4 lg:h-auto lg:flex-col lg:items-start lg:gap-3 lg:px-6 lg:pt-7 lg:pb-8">
            <Link to="/admin" aria-label="AkotoCreative SMS admin home" className="dark flex min-w-0 items-center gap-2 rounded-md text-white">
              <Logo className="text-lg" />
            </Link>
            <span className="hidden shrink-0 items-center gap-1 rounded-full bg-[var(--gold-glow)]/15 px-2 py-0.5 text-[0.7rem] font-semibold tracking-wide text-[var(--gold-glow)] uppercase ring-1 ring-[var(--gold-glow)]/30 ring-inset sm:inline-flex">
              <ShieldCheck className="size-3" aria-hidden /> Admin
            </span>
            <button
              type="button"
              onClick={handleLogout}
              className="ml-auto inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-white/15 px-2.5 py-1.5 text-xs font-medium text-white/80 hover:bg-white/10 lg:hidden"
            >
              <LogOut className="size-3.5" aria-hidden /> Sign out
            </button>
          </div>

          <nav aria-label="Admin sections" className="overflow-x-auto px-4 pb-3 lg:flex-1 lg:px-6 lg:pb-0">
            <p className="mb-2 hidden px-3 text-[0.65rem] font-semibold tracking-[0.18em] text-white/40 uppercase lg:block">
              Console
            </p>
            <ul className="flex w-max gap-1 lg:w-auto lg:flex-col">{navLinks}</ul>
          </nav>

          <div className="hidden p-4 lg:block">
            <div className="glass grid grid-cols-1 gap-3 rounded-2xl p-4">
              <div className="flex min-w-0 items-center gap-3">
                <Avatar email={adminUser.email} className="size-9" />
                <div className="min-w-0 flex-1">
                  <p className="truncate text-sm font-medium text-white" title={adminUser.email ?? undefined}>
                    {adminUser.email}
                  </p>
                  <p className="flex items-center gap-1.5 text-xs text-white/55">
                    <span className="pulse-dot size-1.5 rounded-full bg-emerald-400" aria-hidden /> Signed in as admin
                  </p>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-2">
                <a
                  href="/"
                  target="_blank"
                  rel="noreferrer"
                  className="inline-flex items-center justify-center gap-1.5 rounded-lg bg-white/[0.06] px-2 py-1.5 text-xs font-medium text-white/80 transition-colors hover:bg-white/15 hover:text-white"
                >
                  <ExternalLink className="size-3.5" aria-hidden /> Website
                </a>
                <button
                  type="button"
                  onClick={handleLogout}
                  className="inline-flex items-center justify-center gap-1.5 rounded-lg bg-white/[0.06] px-2 py-1.5 text-xs font-medium text-white/80 transition-colors hover:bg-white/15 hover:text-white"
                >
                  <LogOut className="size-3.5" aria-hidden /> Sign out
                </button>
              </div>
            </div>
          </div>
          <div className="kente-band hidden h-1.5 opacity-80 lg:block" aria-hidden />
        </div>
      </aside>

      <div className="min-w-0">
        <header className="sticky top-0 z-30 hidden border-b bg-background/75 backdrop-blur-xl lg:block">
          <div className="mx-auto flex h-16 max-w-content items-center justify-between gap-4 px-8">
            <p className="flex items-center gap-2 text-sm text-muted-foreground">
              <span>Admin</span>
              <span aria-hidden>/</span>
              <span className="font-medium text-foreground">{current.label}</span>
            </p>
            <p className="inline-flex items-center gap-2 rounded-full border bg-card px-3 py-1.5 text-xs font-medium text-muted-foreground shadow-deep" suppressHydrationWarning>
              <CalendarDays className="size-3.5 text-primary" aria-hidden />
              {todayFormat.format(new Date())}
            </p>
          </div>
        </header>
        <main className="px-4 py-8 sm:px-8 lg:py-10">
          <div className="rise mx-auto max-w-content" key={current.to}>
            <Outlet />
          </div>
        </main>
      </div>
    </div>
  )
}
