import type { FC, PropsWithChildren } from "hono/jsx";
import type { User } from "../db/schema";
import { Layout } from "./layout";

// ---------------------------------------------------------------------------
// AdminShell — the single unified chrome for every /admin/* surface.
//
// Before this, the ~15 admin pages each rendered the plain customer `Layout`
// with no admin navigation, so the only way between admin screens was the
// two rival hub pages (/admin and /admin/command). AdminShell wraps `Layout`
// (so the html shell, top nav, footer, scripts all still work) and adds a
// persistent left sidebar driven by ONE canonical `ADMIN_NAV` array plus a
// sticky page header (title + optional actions slot).
//
// This module is the single source of truth for the admin IA. Every admin
// destination in the app lives in `ADMIN_NAV` below — nothing stays orphaned.
// Migrate a page by replacing its `<Layout …>` wrapper with
// `<AdminShell active="<key>" title="…" user={user}> … </AdminShell>`.
// ---------------------------------------------------------------------------

export type AdminNavKey =
  // Overview
  | "dashboard"
  | "command"
  // Operations & Health
  | "ops"
  | "health"
  | "env-health"
  | "status"
  | "diagnose"
  | "autopilot"
  // Deploys & Infra
  | "deploys"
  | "self-host"
  | "servers"
  // Users & Access
  | "users"
  | "repos"
  | "security"
  | "deletions"
  // Sign-in & SSO
  | "google-oauth"
  | "github-oauth"
  | "sso"
  // Growth & Billing
  | "growth"
  | "billing"
  | "stripe"
  | "digests"
  | "ai-costs"
  // Platform Config
  | "flags"
  | "integrations"
  | "advancement"
  | "connect-claude";

interface AdminNavItem {
  key: AdminNavKey;
  href: string;
  label: string;
}

interface AdminNavGroup {
  label: string;
  items: AdminNavItem[];
}

/**
 * Canonical admin navigation. Grouped by concern; the union of both legacy
 * hubs (/admin + /admin/command) plus the previously-orphaned /admin/servers
 * and /admin/billing surfaces. This array is the ONLY place the admin IA is
 * defined — add new admin pages here and every shell picks them up.
 */
export const ADMIN_NAV: AdminNavGroup[] = [
  {
    label: "Overview",
    items: [
      { key: "dashboard", href: "/admin", label: "Dashboard" },
      { key: "command", href: "/admin/command", label: "Command Center" },
    ],
  },
  {
    label: "Operations & Health",
    items: [
      { key: "ops", href: "/admin/ops", label: "Operations" },
      { key: "health", href: "/admin/health", label: "Health (traffic lights)" },
      { key: "env-health", href: "/admin/env-health", label: "Env / feature health" },
      { key: "status", href: "/admin/status", label: "Platform monitor" },
      { key: "diagnose", href: "/admin/diagnose", label: "AI background tasks" },
      { key: "autopilot", href: "/admin/autopilot", label: "Autopilot" },
    ],
  },
  {
    label: "Deploys & Infra",
    items: [
      { key: "deploys", href: "/admin/deploys", label: "Deploys" },
      { key: "self-host", href: "/admin/self-host", label: "Self-host status" },
      { key: "servers", href: "/admin/servers", label: "Server targets" },
    ],
  },
  {
    label: "Users & Access",
    items: [
      { key: "users", href: "/admin/users", label: "Manage users" },
      { key: "repos", href: "/admin/repos", label: "Manage repos" },
      { key: "security", href: "/admin/security", label: "Security" },
      { key: "deletions", href: "/admin/deletions", label: "GDPR deletions" },
    ],
  },
  {
    label: "Sign-in & SSO",
    items: [
      { key: "google-oauth", href: "/admin/google-oauth", label: "Sign in with Google" },
      { key: "github-oauth", href: "/admin/github-oauth", label: "Sign in with GitHub" },
      { key: "sso", href: "/admin/sso", label: "Enterprise SSO" },
    ],
  },
  {
    label: "Growth & Billing",
    items: [
      { key: "growth", href: "/admin/growth", label: "User growth" },
      { key: "billing", href: "/admin/billing", label: "Billing" },
      { key: "stripe", href: "/admin/stripe", label: "Stripe sync" },
      { key: "digests", href: "/admin/digests", label: "Email digests" },
      { key: "ai-costs", href: "/admin/ai-costs", label: "AI cost breakdown" },
    ],
  },
  {
    label: "Platform Config",
    items: [
      { key: "flags", href: "/admin/flags", label: "Site flags" },
      { key: "integrations", href: "/admin/integrations", label: "Integrations" },
      { key: "advancement", href: "/admin/advancement", label: "Advancement" },
      { key: "connect-claude", href: "/connect/claude", label: "Connect Claude" },
    ],
  },
];

export const AdminShell: FC<
  PropsWithChildren<{
    active: AdminNavKey | string;
    title: string;
    user?: User | null;
    // Optional right-aligned actions slot rendered in the sticky page header.
    actions?: any;
  }>
> = ({ active, title, user, actions, children }) => (
  <Layout title={`${title} — Admin`} user={user}>
    <style dangerouslySetInnerHTML={{ __html: adminShellStyles }} />
    <div class="admin-shell">
      <aside class="admin-shell-sidebar">
        <div class="admin-shell-brand">
          <span class="admin-shell-brand-dot" aria-hidden="true" />
          Site admin
        </div>
        <nav class="adminnav" aria-label="Admin sections">
          {ADMIN_NAV.map((group) => (
            <div class="adminnav-group">
              <div class="adminnav-label">{group.label}</div>
              {group.items.map((it) => (
                <a
                  href={it.href}
                  class={it.key === active ? "is-active" : ""}
                  aria-current={it.key === active ? "page" : undefined}
                >
                  {it.label}
                </a>
              ))}
            </div>
          ))}
        </nav>
      </aside>
      <div class="admin-shell-main">
        <header class="admin-shell-head">
          <h1 class="admin-shell-title">{title}</h1>
          {actions ? (
            <div class="admin-shell-actions">{actions}</div>
          ) : null}
        </header>
        <div class="admin-shell-content">{children}</div>
      </div>
    </div>
  </Layout>
);

/**
 * Shell CSS. Follows the SettingsNav pattern (grouped sidebar, sticky, token
 * based, theme-aware). No hardcoded hex — every colour resolves from a design
 * token so light/dark both track automatically. Injected once per page; a
 * duplicate identical <style> is harmless.
 */
export const adminShellStyles = `
  .admin-shell {
    display: grid;
    grid-template-columns: 240px minmax(0, 1fr);
    gap: var(--space-6);
    align-items: start;
    max-width: 1280px;
    margin: 0 auto;
    padding: var(--space-6) var(--space-6) var(--space-16);
  }
  .admin-shell-sidebar {
    position: sticky;
    top: var(--space-4);
    display: flex;
    flex-direction: column;
    gap: var(--space-4);
    min-width: 0;
  }
  .admin-shell-brand {
    display: flex;
    align-items: center;
    gap: var(--space-2);
    font-family: var(--font-mono);
    font-size: var(--font-size-xs);
    font-weight: 500;
    letter-spacing: 0.12em;
    text-transform: uppercase;
    color: var(--text-muted);
    padding: 0 var(--space-2);
  }
  .admin-shell-brand-dot {
    width: 7px;
    height: 7px;
    border-radius: var(--radius-full);
    background: var(--accent);
    box-shadow: var(--accent-glow);
  }
  .adminnav {
    display: flex;
    flex-direction: column;
    gap: var(--space-5);
  }
  .adminnav-group {
    display: flex;
    flex-direction: column;
    gap: 1px;
  }
  .adminnav-label {
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 0.06em;
    text-transform: uppercase;
    color: var(--text-muted);
    padding: 4px 10px;
    margin-bottom: 2px;
  }
  .adminnav a {
    display: block;
    padding: 6px 10px;
    border-radius: 6px;
    font-size: 13.5px;
    font-weight: 500;
    color: var(--text-muted);
    text-decoration: none;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    transition: background var(--t-fast) var(--ease), color var(--t-fast) var(--ease);
  }
  .adminnav a:hover {
    color: var(--text-strong);
    background: var(--bg-hover);
  }
  .adminnav a.is-active {
    color: var(--text-strong);
    background: var(--accent-gradient-soft);
    box-shadow: var(--accent-glow) inset;
    font-weight: 600;
  }
  .admin-shell-main {
    min-width: 0;
  }
  .admin-shell-head {
    position: sticky;
    top: 0;
    z-index: var(--z-sticky);
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: var(--space-4);
    flex-wrap: wrap;
    padding: var(--space-4) 0;
    margin-bottom: var(--space-5);
    border-bottom: 1px solid var(--border);
    background: var(--bg);
  }
  .admin-shell-title {
    font-family: var(--font-display);
    font-size: var(--font-size-xl);
    font-weight: 700;
    letter-spacing: -0.022em;
    color: var(--text-strong);
    margin: 0;
    min-width: 0;
  }
  .admin-shell-actions {
    display: flex;
    align-items: center;
    gap: var(--space-2);
    flex-wrap: wrap;
  }
  .admin-shell-content {
    min-width: 0;
  }
  @media (max-width: 860px) {
    .admin-shell {
      display: block;
      padding: var(--space-4);
    }
    .admin-shell-sidebar {
      position: static;
      margin-bottom: var(--space-5);
    }
    .adminnav {
      flex-direction: row;
      flex-wrap: wrap;
      gap: var(--space-3);
      padding: var(--space-2);
      background: var(--bg-elevated);
      border: 1px solid var(--border);
      border-radius: var(--radius);
    }
    .adminnav-group {
      flex-direction: row;
      flex-wrap: wrap;
      gap: 2px;
    }
    .adminnav-label {
      display: none;
    }
    .adminnav a {
      padding: 6px 12px;
      border-radius: var(--radius-full);
    }
    .admin-shell-head {
      position: static;
    }
  }
`;
