"use client";

import { useState } from "react";
import type { Session } from "next-auth";
import Link from "next/link";
import { ArrowLeft, Globe2, Menu, ShieldCheck, X } from "lucide-react";
import { ReferenceBrandLogo } from "@/components/dashboard/reference-brand-logo";
import { AdminNav } from "@/components/admin/admin-nav";
import { useLanguage } from "@/lib/i18n/context";
import { dashboardInter } from "@/lib/fonts/dashboard-font";

const LANGUAGE_OPTIONS = [
  { locale: "es" as const, label: "ES" },
  { locale: "en" as const, label: "ENG" },
];

function initials(name?: string | null, email?: string | null) {
  if (name) {
    const parts = name.trim().split(/\s+/);
    return `${parts[0]?.[0] ?? ""}${parts[1]?.[0] ?? ""}`.toUpperCase() || "?";
  }
  return email?.[0]?.toUpperCase() ?? "?";
}

function LanguageSwitch() {
  const { locale, setLocale } = useLanguage();

  return (
    <div className="sidebar-language" role="group" aria-label="Language">
      <span className="sidebar-language-icon" aria-hidden="true"><Globe2 /></span>
      <span className="sidebar-language-options">
        {LANGUAGE_OPTIONS.map((option) => (
          <button
            key={option.locale}
            type="button"
            onClick={() => setLocale(option.locale)}
            aria-pressed={locale === option.locale}
            className={locale === option.locale ? "active" : undefined}
          >
            {option.label}
          </button>
        ))}
      </span>
    </div>
  );
}

function AdminSidebar({ user, inDrawer = false, onNavigate }: { user: Session["user"]; inDrawer?: boolean; onNavigate?: () => void }) {
  const { t } = useLanguage();
  const a = t.admin;
  const displayName = user.name || user.firstName || user.email || "Admin";

  return (
    <aside className={`sidebar${inDrawer ? " sidebar-drawer" : ""}`}>
      <div className="brand">
        <ReferenceBrandLogo className="brand-mark" />
        <div className="brand-copy">
          <div className="brand-name">Tok<span>Next</span></div>
          <div className="brand-sub">{t.dashboard.sidebar.tagline}</div>
        </div>
      </div>

      <div className="admin-rail-badge"><ShieldCheck /> <span>{a.title}</span></div>
      <AdminNav onNavigate={onNavigate} />

      <div className="sidebar-footer-tools">
        <LanguageSwitch />
        <Link href="/dashboard" className="admin-dashboard-link nav-item nav-tone-blue" onClick={onNavigate}>
          <span className="nav-icon-shell"><ArrowLeft /></span>
          {a.nav.backToDashboard}
        </Link>
        <div className="account-profile" aria-label={displayName}>
          <span className="account-avatar">{initials(user.name, user.email)}</span>
          <span className="account-copy">
            <strong>{displayName}</strong>
            <small>{a.title}</small>
          </span>
          <ShieldCheck className="account-chevron" aria-hidden="true" />
        </div>
      </div>
    </aside>
  );
}

export function AdminShell({ user, children }: { user: Session["user"]; children: React.ReactNode }) {
  const { t } = useLanguage();
  const [mobileOpen, setMobileOpen] = useState(false);

  return (
    <div className={`tn-dashboard-reference dashboard-inter ${dashboardInter.variable} flex-1`}>
      <div className="app">
        <AdminSidebar user={user} />

        {mobileOpen && (
          <div className="admin-mobile-overlay" role="presentation" onClick={() => setMobileOpen(false)}>
            <div className="admin-mobile-drawer" onClick={(event) => event.stopPropagation()}>
              <button type="button" className="admin-mobile-close" onClick={() => setMobileOpen(false)} aria-label="Close menu"><X /></button>
              <AdminSidebar user={user} inDrawer onNavigate={() => setMobileOpen(false)} />
            </div>
          </div>
        )}

        <main className="main workspace-light text-foreground">
          <header className="admin-shell-topbar">
            <div className="admin-shell-heading">
              <button type="button" className="control icon-control admin-mobile-menu" onClick={() => setMobileOpen(true)} aria-label="Open menu">
                <Menu />
              </button>
              <div>
                <span className="admin-shell-eyebrow">TokNext Control Center</span>
                <h1>{t.admin.title}</h1>
              </div>
            </div>
            <div className="admin-shell-actions">
              <Link href="/dashboard" className="admin-shell-return">{t.admin.nav.backToDashboard}<ArrowLeft /></Link>
              <span className="admin-shell-avatar" aria-hidden="true">{initials(user.name, user.email)}</span>
            </div>
          </header>
          {children}
        </main>
      </div>
    </div>
  );
}
