"use client";

import {
  Activity,
  Bot,
  Check,
  ChevronsUpDown,
  Database,
  Gavel,
  Github,
  LayoutDashboard,
  LogOut,
  Menu,
  Plug,
  Plus,
  ScrollText,
  Users,
  Workflow,
  X,
} from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { Wordmark } from "@/components/brand";
import { Button, Input, PageLoader } from "@/components/ui";
import { useAuth } from "@/lib/auth";
import { accentForPath, PAGE_ACCENTS } from "@/lib/nav-theme";
import { cn } from "@/lib/utils";

export const GITHUB_URL = "https://github.com/sanmaxdev/legate-agent";

const NAV = [
  {
    group: "Overview",
    items: [{ href: "/dashboard", label: "Dashboard", icon: LayoutDashboard }],
  },
  {
    group: "Build",
    items: [
      { href: "/agents", label: "Agents", icon: Bot },
      { href: "/workflows", label: "Workflows", icon: Workflow },
      { href: "/knowledge", label: "Knowledge", icon: Database },
      { href: "/connectors", label: "Connectors", icon: Plug },
    ],
  },
  {
    group: "Operate",
    items: [
      { href: "/runs", label: "Runs", icon: Activity },
      { href: "/approvals", label: "Approvals", icon: Gavel },
    ],
  },
  {
    group: "Govern",
    items: [
      { href: "/audit", label: "Audit", icon: ScrollText },
      { href: "/admin", label: "Admin", icon: Users },
    ],
  },
];

function WorkspaceSwitcher() {
  const { workspaces, currentWorkspace, switchWorkspace, createWorkspace } = useAuth();
  const [open, setOpen] = useState(false);
  const [creating, setCreating] = useState(false);
  const [name, setName] = useState("");

  return (
    <div className="relative">
      <button
        onClick={() => setOpen((v) => !v)}
        className="flex items-center gap-2 rounded-lg border border-line bg-surface/60 px-3 py-1.5 text-sm transition-colors hover:border-line-strong"
      >
        <span className="flex h-5 w-5 items-center justify-center rounded bg-accent/15 font-mono text-[11px] font-semibold text-accent">
          {currentWorkspace?.name?.[0]?.toUpperCase() ?? "?"}
        </span>
        <span className="max-w-[10rem] truncate font-medium text-fg">
          {currentWorkspace?.name ?? "No workspace"}
        </span>
        <ChevronsUpDown className="h-3.5 w-3.5 text-faint" />
      </button>
      {open && (
        <>
          <div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />
          <div className="absolute left-0 z-20 mt-2 w-64 rounded-xl border border-line-strong bg-surface p-1.5 shadow-panel">
            <div className="px-2 py-1.5 eyebrow">Workspaces</div>
            {workspaces.map((w) => (
              <button
                key={w.id}
                onClick={() => {
                  void switchWorkspace(w.id);
                  setOpen(false);
                }}
                className="flex w-full items-center justify-between rounded-lg px-2 py-1.5 text-sm text-fg transition-colors hover:bg-surface-2"
              >
                <span className="flex items-center gap-2">
                  <span className="flex h-5 w-5 items-center justify-center rounded bg-accent/15 font-mono text-[11px] text-accent">
                    {w.name[0]?.toUpperCase()}
                  </span>
                  {w.name}
                </span>
                {w.id === currentWorkspace?.id && <Check className="h-4 w-4 text-accent" />}
              </button>
            ))}
            <div className="my-1 hairline" />
            {creating ? (
              <form
                className="flex gap-1.5 p-1"
                onSubmit={async (e) => {
                  e.preventDefault();
                  if (!name.trim()) return;
                  await createWorkspace(name.trim());
                  setName("");
                  setCreating(false);
                  setOpen(false);
                }}
              >
                <Input
                  autoFocus
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="Workspace name"
                  className="h-8"
                />
                <Button size="sm" variant="primary" type="submit">
                  Add
                </Button>
              </form>
            ) : (
              <button
                onClick={() => setCreating(true)}
                className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-sm text-muted transition-colors hover:bg-surface-2 hover:text-fg"
              >
                <Plus className="h-4 w-4" /> New workspace
              </button>
            )}
          </div>
        </>
      )}
    </div>
  );
}

function Sidebar({ onNavigate }: { onNavigate?: () => void }) {
  const pathname = usePathname();
  const { currentWorkspace, role, logout } = useAuth();
  return (
    <div className="flex h-full flex-col">
      <div className="px-5 py-6">
        <Wordmark />
      </div>
      <nav className="flex-1 space-y-6 overflow-y-auto px-3">
        {NAV.map((section) => (
          <div key={section.group}>
            <div className="px-3 pb-2 eyebrow">{section.group}</div>
            <div className="space-y-0.5">
              {section.items.map((item) => {
                const active = pathname.startsWith(item.href);
                const Icon = item.icon;
                const color = `rgb(${PAGE_ACCENTS[item.href] ?? "245 165 36"})`;
                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    onClick={onNavigate}
                    className={cn(
                      "group relative flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors",
                      active
                        ? "bg-surface-2 text-fg"
                        : "text-muted hover:bg-surface-2/60 hover:text-fg"
                    )}
                  >
                    {active && (
                      <span
                        className="absolute left-0 top-1/2 h-5 w-0.5 -translate-y-1/2 rounded-full"
                        style={{ backgroundColor: color }}
                      />
                    )}
                    <Icon
                      className={cn(
                        "h-[18px] w-[18px] transition-opacity",
                        active ? "opacity-100" : "opacity-75 group-hover:opacity-100"
                      )}
                      style={{ color }}
                    />
                    {item.label}
                  </Link>
                );
              })}
            </div>
          </div>
        ))}
      </nav>
      <div className="m-3 rounded-xl border border-line bg-surface/50 p-3">
        <div className="flex items-center justify-between">
          <div className="min-w-0">
            <div className="truncate text-sm font-medium text-fg">
              {currentWorkspace?.name ?? "-"}
            </div>
            <div className="font-mono text-[11px] uppercase tracking-wider text-accent">
              {role ?? "-"}
            </div>
          </div>
          <button
            onClick={logout}
            title="Sign out"
            className="rounded-lg p-2 text-faint transition-colors hover:bg-surface-2 hover:text-danger"
          >
            <LogOut className="h-4 w-4" />
          </button>
        </div>
      </div>
    </div>
  );
}

function NoWorkspace() {
  const { createWorkspace } = useAuth();
  const [name, setName] = useState("");
  const [loading, setLoading] = useState(false);
  return (
    <div className="flex min-h-screen items-center justify-center p-6">
      <div className="panel w-full max-w-md p-8 text-center animate-fade-up">
        <Wordmark className="mb-6 flex justify-center" />
        <h1 className="font-display text-2xl font-bold text-fg">Create your workspace</h1>
        <p className="mt-2 text-sm text-muted">
          A workspace is your isolated tenant. Agents, connectors, runs, and audit all live inside
          it.
        </p>
        <form
          className="mt-6 flex gap-2"
          onSubmit={async (e) => {
            e.preventDefault();
            if (!name.trim()) return;
            setLoading(true);
            try {
              await createWorkspace(name.trim());
            } finally {
              setLoading(false);
            }
          }}
        >
          <Input
            autoFocus
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Acme Inc."
          />
          <Button variant="primary" type="submit" loading={loading}>
            Create
          </Button>
        </form>
      </div>
    </div>
  );
}

export function AppShell({ children }: { children: React.ReactNode }) {
  const { booting, isAuthed, currentWorkspace, workspaces } = useAuth();
  const router = useRouter();
  const pathname = usePathname();
  const [drawer, setDrawer] = useState(false);

  useEffect(() => {
    if (!booting && !isAuthed) router.replace("/login");
  }, [booting, isAuthed, router]);

  if (booting) return <PageLoader />;
  if (!isAuthed) return <PageLoader />;
  if (!currentWorkspace && workspaces.length === 0) return <NoWorkspace />;

  return (
    <div className="min-h-screen lg:grid lg:grid-cols-[268px_1fr]">
      {/* Desktop sidebar */}
      <aside className="sticky top-0 hidden h-screen border-r border-line bg-ink/40 lg:block">
        <Sidebar />
      </aside>

      {/* Mobile drawer */}
      {drawer && (
        <div className="fixed inset-0 z-40 lg:hidden">
          <div
            className="fixed inset-0 bg-ink/70 backdrop-blur-sm"
            onClick={() => setDrawer(false)}
          />
          <aside className="fixed left-0 top-0 h-full w-[268px] border-r border-line bg-surface">
            <button
              onClick={() => setDrawer(false)}
              className="absolute right-3 top-6 rounded-lg p-1.5 text-faint hover:text-fg"
            >
              <X className="h-5 w-5" />
            </button>
            <Sidebar onNavigate={() => setDrawer(false)} />
          </aside>
        </div>
      )}

      <div
        className="flex min-h-screen flex-col"
        style={{ ["--accent" as string]: accentForPath(pathname) } as React.CSSProperties}
      >
        <header className="sticky top-0 z-30 flex h-16 items-center gap-3 border-b border-line bg-ink/70 px-4 backdrop-blur-md sm:px-6">
          <button
            onClick={() => setDrawer(true)}
            className="rounded-lg p-2 text-muted hover:bg-surface-2 lg:hidden"
          >
            <Menu className="h-5 w-5" />
          </button>
          <WorkspaceSwitcher />
          <div className="flex-1" />
          <a
            href={GITHUB_URL}
            target="_blank"
            rel="noreferrer"
            className="hidden font-mono text-[11px] uppercase tracking-wider text-faint transition-colors hover:text-muted sm:block"
          >
            self-hosted
          </a>
        </header>
        <main className="mx-auto w-full max-w-6xl flex-1 px-4 py-8 sm:px-6 lg:px-8">
          {children}
        </main>
      </div>

      {/* Persistent, low-key link back to the source. */}
      <a
        href={GITHUB_URL}
        target="_blank"
        rel="noreferrer"
        className="fixed bottom-4 right-4 z-20 hidden items-center gap-1.5 rounded-full border border-line bg-surface/70 px-3 py-1.5 font-mono text-[11px] text-muted opacity-40 backdrop-blur-sm transition-opacity hover:opacity-100 sm:flex"
      >
        <Github className="h-3.5 w-3.5" /> GitHub
      </a>
    </div>
  );
}
