import { Link, useNavigate, useRouterState } from "@tanstack/react-router";
import { LayoutDashboard, Users, Send, FileText, BarChart3, Settings, LogOut, MessageSquare, Menu, X, ArrowUpRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { supabase } from "@/integrations/supabase/client";
import { useQueryClient } from "@tanstack/react-query";
import { useState, type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { GatavaseAiWidget } from "@/components/gatavase-ai";

const NAV = [
  { to: "/dashboard", label: "Overview", icon: LayoutDashboard },
  { to: "/dashboard/contacts", label: "Contacts", icon: Users },
  { to: "/dashboard/campaigns", label: "Campaigns", icon: Send },
  { to: "/dashboard/templates", label: "Templates", icon: FileText },
  { to: "/dashboard/analytics", label: "Analytics", icon: BarChart3 },
  { to: "/dashboard/settings", label: "Settings", icon: Settings },
] as const;

export function DashboardShell({ children, title, action }: { children: ReactNode; title: string; action?: ReactNode }) {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const [open, setOpen] = useState(false);

  const signOut = async () => {
    await queryClient.cancelQueries();
    queryClient.clear();
    await supabase.auth.signOut();
    navigate({ to: "/auth", replace: true });
  };

  return (
    <div className="min-h-screen bg-muted/30">
      {/* Sidebar */}
      <aside className={cn(
        "fixed inset-y-0 left-0 z-40 w-64 transform border-r border-sidebar-border bg-sidebar text-sidebar-foreground transition-transform lg:translate-x-0",
        open ? "translate-x-0" : "-translate-x-full"
      )}>
        <div className="flex h-20 items-center gap-3 border-b border-sidebar-border px-5">
          <div className="grid h-9 w-9 place-items-center rounded-lg bg-sidebar-primary">
            <MessageSquare className="h-5 w-5 text-sidebar-primary-foreground" />
          </div>
          <div>
            <div className="font-display text-base font-bold leading-tight">Gatavase</div>
            <div className="text-[10px] uppercase tracking-wider text-sidebar-foreground/60">Bulky SMS</div>
          </div>
        </div>
        <p className="px-6 pt-6 text-xs font-medium text-sidebar-foreground/50">WORKSPACE</p>
        <nav className="space-y-1 px-3 py-4" aria-label="Workspace">
          {NAV.map((item) => {
            const active = pathname === item.to || (item.to !== "/dashboard" && pathname.startsWith(item.to));
            return (
              <Link
                key={item.to}
                to={item.to}
                onClick={() => setOpen(false)}
                aria-current={active ? "page" : undefined}
                className={cn(
                  "flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition",
                  active
                    ? "bg-sidebar-accent text-sidebar-primary"
                    : "text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground"
                )}
              >
                <item.icon className="h-4 w-4" /> {item.label}
              </Link>
            );
          })}
        </nav>
        <div className="absolute inset-x-3 bottom-4 space-y-3">
          <Link to="/contact" className="flex items-center justify-between border-t border-sidebar-border px-3 pt-4 text-sm text-sidebar-foreground/70">Contact support <ArrowUpRight className="h-4 w-4" /></Link>
          <Button variant="ghost" onClick={signOut} className="w-full justify-start gap-3 text-sidebar-foreground/70 hover:bg-sidebar-accent hover:text-sidebar-foreground"><LogOut className="h-4 w-4" /> Sign out</Button>
          <p className="px-3 text-[10px] text-sidebar-foreground/40">Powered by Gatavase Corporation</p>
        </div>
      </aside>

      {/* Main */}
      <div className="lg:pl-64">
        <header className="sticky top-0 z-30 flex min-h-20 flex-wrap items-center justify-between gap-3 py-3 border-b border-border bg-background/80 px-4 backdrop-blur-xl sm:px-6">
          <div className="flex min-w-0 items-center gap-3">
            <Button variant="ghost" size="icon" className="lg:hidden" aria-label="Toggle navigation menu" aria-expanded={open} onClick={() => setOpen((o) => !o)}>
              {open ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
            </Button>
            <h1 className="font-display text-xl font-semibold break-words">{title}</h1>
          </div>
          <div>{action}</div>
        </header>
        <main className="p-4 sm:p-6 lg:p-8">{children}</main>
      </div>

      {open && <div className="fixed inset-0 z-30 bg-foreground/30 lg:hidden" onClick={() => setOpen(false)} />}
      <GatavaseAiWidget />
    </div>
  );
}
