import { Link, useRouterState } from "@tanstack/react-router";
import { Home, ScanLine, CalendarCheck, FileText, User, Bell, Shield, Building2, Receipt } from "lucide-react";
import type { ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import logo from "@/assets/logo.png";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/lib/use-auth";

const nav = [
  { to: "/", label: "Home", icon: Home },
  { to: "/check", label: "Scan", icon: ScanLine },
  { to: "/book", label: "Book", icon: CalendarCheck },
  { to: "/services", label: "Services", icon: FileText },
  { to: "/dashboard", label: "Account", icon: User },
] as const;

export function BrandMark({ className = "h-9 w-9" }: { className?: string }) {
  return <img src={logo} alt="Emma Mold Inspection Services logo" className={className} width={512} height={512} />;
}

function NotificationBell() {
  const { user } = useAuth();
  const { data: unread } = useQuery({
    queryKey: ["unread-notifications", user?.id],
    enabled: Boolean(user),
    refetchInterval: 60000,
    queryFn: async () => {
      const { count, error } = await supabase
        .from("notifications")
        .select("id", { count: "exact", head: true })
        .eq("user_id", user!.id)
        .eq("read", false);
      if (error) throw error;
      return count ?? 0;
    },
  });

  if (!user) return null;

  return (
    <Link to="/notifications" aria-label="Notifications" className="relative rounded-full p-2 hover:bg-muted">
      <Bell className="h-5 w-5" />
      {unread ? (
        <span className="absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-bold text-primary-foreground">
          {unread > 9 ? "9+" : unread}
        </span>
      ) : null}
    </Link>
  );
}

function PortalLink() {
  const { isAdmin, isProvider } = useAuth();
  if (isAdmin)
    return (
      <Link to="/admin" aria-label="Admin portal" className="rounded-full p-2 hover:bg-muted">
        <Shield className="h-5 w-5" />
      </Link>
    );
  if (isProvider)
    return (
      <Link to="/provider" aria-label="Service provider portal" className="rounded-full p-2 hover:bg-muted">
        <Building2 className="h-5 w-5" />
      </Link>
    );
  return null;
}

export function AppShell({ children }: { children: ReactNode }) {
  const pathname = useRouterState({ select: (s) => s.location.pathname });

  return (
    <div className="min-h-screen bg-background pb-24">
      <header className="sticky top-0 z-30 border-b border-border/60 bg-background/85 backdrop-blur">
        <div className="mx-auto flex max-w-3xl items-center justify-between px-4 py-3">
          <Link to="/" className="flex items-center gap-2">
            <BrandMark />
            <span className="leading-tight">
              <span className="block text-sm font-semibold">Emma Mold</span>
              <span className="block text-[11px] text-muted-foreground">Inspection Services</span>
            </span>
          </Link>
          <div className="flex items-center gap-1">
            <PortalLink />
            <Link to="/quotes" aria-label="Quotations and invoices" className="rounded-full p-2 hover:bg-muted">
              <Receipt className="h-5 w-5" />
            </Link>
            <NotificationBell />
            <Link
              to="/book"
              search={{ service: undefined, company: undefined }}
              className="rounded-full bg-brand px-4 py-2 text-xs font-semibold text-primary-foreground shadow-card"
            >
              Book now
            </Link>
          </div>
        </div>
      </header>

      <main className="mx-auto w-full max-w-3xl px-4 py-5">{children}</main>

      <nav className="fixed inset-x-0 bottom-0 z-30 border-t border-border/60 bg-background/95 backdrop-blur">
        <div className="mx-auto flex max-w-3xl items-stretch justify-between px-2 py-2">
          {nav.map((item) => {
            const active = item.to === "/" ? pathname === "/" : pathname.startsWith(item.to);
            const Icon = item.icon;
            return (
              <Link
                key={item.to}
                to={item.to}
                className={`flex flex-1 flex-col items-center gap-1 rounded-xl px-2 py-1.5 text-[11px] font-medium transition-colors ${
                  active ? "bg-muted text-primary" : "text-muted-foreground hover:text-foreground"
                }`}
              >
                <Icon className="h-5 w-5" aria-hidden />
                {item.label}
              </Link>
            );
          })}
        </div>
      </nav>
    </div>
  );
}