import { createFileRoute, Outlet, redirect, Link, useLocation } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { supabase } from "@/integrations/supabase/client";
import { LayoutDashboard, Users, Settings, Wallet, FileText, Wifi, Cog, ShieldCheck, Megaphone, KeyRound, Receipt, Gift, BellRing, FlaskConical, Server } from "lucide-react";
import { cn } from "@/lib/utils";
import { ThemeToggle } from "@/components/ThemeToggle";
import { adminMyAccess } from "@/lib/admin.functions";
import { isStaffRole, ROLE_LABELS, type Permission, type StaffRole } from "@/lib/permissions";

export const Route = createFileRoute("/admin")({
  beforeLoad: async () => {
    if (typeof window !== "undefined") {
      const { data, error } = await supabase.auth.getUser();
      if (error || !data.user) throw redirect({ to: "/login" });
      const { data: roles } = await supabase
        .from("user_roles").select("role").eq("user_id", data.user.id);
      const isStaff = (roles ?? []).some((r) => isStaffRole(r.role as string));
      if (!isStaff) throw redirect({ to: "/app" });
    }
  },
  component: AdminLayout,
});

const tabs: { to: string; label: string; icon: typeof Users; perm: Permission }[] = [
  { to: "/admin", label: "Overview", icon: LayoutDashboard, perm: "dashboard.view" },
  { to: "/admin/users", label: "Users", icon: Users, perm: "users.view" },
  { to: "/admin/services", label: "Services", icon: Settings, perm: "plans.view" },
  { to: "/admin/data-plans", label: "Data Plans", icon: Wifi, perm: "plans.view" },
  { to: "/admin/credit", label: "Wallet Ops", icon: Wallet, perm: "wallet.credit" },
  { to: "/admin/transactions", label: "Transactions", icon: Receipt, perm: "transactions.view" },
  { to: "/admin/gift-cards", label: "Gift Cards", icon: Gift, perm: "giftcards.manage" },
  { to: "/admin/banners", label: "Banners", icon: Megaphone, perm: "banners.manage" },
  { to: "/admin/push", label: "Push", icon: BellRing, perm: "push.send" },
  { to: "/admin/providers", label: "API Keys", icon: KeyRound, perm: "providers.manage" },
  { to: "/admin/funding-test", label: "Funding Test", icon: FlaskConical, perm: "funding.test" },
  { to: "/admin/audit", label: "Audit", icon: FileText, perm: "audit.view" },
  { to: "/admin/settings", label: "Settings", icon: Cog, perm: "settings.manage" },
  { to: "/admin/system", label: "System", icon: Server, perm: "settings.manage" },
];

function AdminLayout() {
  const { pathname } = useLocation();
  const fetchAccess = useServerFn(adminMyAccess);
  const { data: access } = useQuery({
    queryKey: ["admin-access"],
    queryFn: () => fetchAccess(),
    staleTime: 60_000,
  });

  const permissions = (access?.permissions ?? []) as Permission[];
  const roles = (access?.roles ?? []) as StaffRole[];
  const visible = access ? tabs.filter((t) => permissions.includes(t.perm)) : [];

  return (
    <div className="min-h-screen bg-background">
      <header className="border-b bg-primary px-4 py-4 text-primary-foreground">
        <div className="mx-auto flex max-w-6xl items-center justify-between">
          <div className="flex items-center gap-2">
            <ShieldCheck className="h-5 w-5" />
            <div>
              <h1 className="text-lg font-bold leading-tight">Billsline Admin</h1>
              {roles.length > 0 && (
                <p className="text-[11px] opacity-80">{roles.map((r) => ROLE_LABELS[r]).join(" · ")}</p>
              )}
            </div>
          </div>
          <div className="flex items-center gap-2">
            <ThemeToggle />
            <Link to="/app" className="text-xs underline opacity-80">Back to app</Link>
          </div>
        </div>
      </header>
      <nav className="border-b bg-card">
        <div className="mx-auto flex max-w-6xl gap-1 overflow-x-auto px-2">
          {visible.map(({ to, label, icon: Icon }) => {
            const active = pathname === to;
            return (
              <Link key={to} to={to}
                className={cn("flex items-center gap-2 whitespace-nowrap border-b-2 px-4 py-3 text-sm font-medium transition-colors",
                  active ? "border-primary text-primary" : "border-transparent text-muted-foreground hover:text-foreground")}>
                <Icon className="h-4 w-4" />{label}
              </Link>
            );
          })}
        </div>
      </nav>
      <main className="mx-auto max-w-6xl p-4">
        <Outlet />
      </main>
    </div>
  );
}
