import { Link, useNavigate } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import { Home, LogOut, Receipt, ShieldCheck } from "lucide-react";
import type { ReactNode } from "react";

import { supabase } from "@/integrations/supabase/client";
import { useSesi } from "@/lib/auth";
import logoAsset from "@/assets/logo-smn.png.asset.json";

type Tujuan = "/dashboard" | "/riwayat" | "/admin";

export function AppShell({ children }: { children: ReactNode }) {
  const { nama, isAdmin } = useSesi();
  const navigate = useNavigate();
  const qc = useQueryClient();

  async function keluar() {
    await qc.cancelQueries();
    qc.clear();
    await supabase.auth.signOut();
    navigate({ to: "/auth", replace: true });
  }

  return (
    <div className="min-h-screen bg-background pb-24">
      <header className="sticky top-0 z-20 border-b border-border/70 bg-background/85 backdrop-blur">
        <div className="mx-auto flex max-w-2xl items-center gap-3 px-4 py-3">
          <img
            src={logoAsset.url}
            alt="Logo Swadaya Muda Network"
            className="h-9 w-auto shrink-0 object-contain sm:h-10"
            width={160}
            height={40}
          />
          <div className="min-w-0 flex-1">
            <p className="truncate text-sm font-semibold leading-tight">
              {nama ? `Halo, ${nama}` : "Catatan duit tanpa ribet"}
            </p>
            <p className="truncate text-xs leading-tight text-muted-foreground">
              {isAdmin ? "Administrator · kas besar & petty cash" : "Pengguna operasional · petty cash"}
            </p>
          </div>
          <button
            type="button"
            onClick={keluar}
            aria-label="Keluar"
            className="flex size-9 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
          >
            <LogOut className="size-4" />
          </button>
        </div>
      </header>

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

      <nav className="fixed inset-x-0 bottom-0 z-20 border-t border-border/70 bg-background/95 backdrop-blur">
        <div className="mx-auto flex max-w-2xl items-stretch">
          <NavItem to="/dashboard" label="Beranda" icon={<Home className="size-5" />} />
          <NavItem to="/riwayat" label="Riwayat" icon={<Receipt className="size-5" />} />
          {isAdmin && (
            <NavItem to="/admin" label="Kas besar" icon={<ShieldCheck className="size-5" />} />
          )}
        </div>
      </nav>
    </div>
  );
}

function NavItem({ to, label, icon }: { to: Tujuan; label: string; icon: ReactNode }) {
  return (
    <Link
      to={to}
      className="flex flex-1 flex-col items-center gap-1 py-3 text-xs text-muted-foreground transition-colors"
      activeProps={{ className: "text-primary font-medium" }}
    >
      {icon}
      {label}
    </Link>
  );
}
