"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import type { CurrentUser } from "@capila/contracts";
import { ProfileAvatar } from "@/components/profile-avatar";
import type { Dictionary, Locale } from "@/lib/i18n";
import { LanguageSwitcher } from "../language-switcher";
import { ThemeSwitcher, type Theme } from "../theme-switcher";
import { logout } from "../login/actions";

type DomainLink = { slug: string; label: string };

export function PanelShell({
  children,
  user,
  locale,
  dictionary,
  domainLinks,
  theme,
}: {
  children: React.ReactNode;
  user: CurrentUser;
  locale: Locale;
  dictionary: Dictionary;
  domainLinks: DomainLink[];
  theme: Theme;
}) {
  const pathname = usePathname();
  const [menuOpen, setMenuOpen] = useState(false);
  const [isInteractive, setIsInteractive] = useState(false);

  useEffect(() => setIsInteractive(true), []);
  useEffect(() => setMenuOpen(false), [pathname]);
  useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => {
      document.body.style.overflow = "";
    };
  }, [menuOpen]);

  const isActive = (href: string) =>
    href === "/dashboard" ? pathname === href : pathname.startsWith(href);

  return (
    <div
      className="panel-shell"
      data-interactive={isInteractive || undefined}
      data-menu-open={menuOpen || undefined}
    >
      <button
        type="button"
        className="sidebar-backdrop"
        aria-label={dictionary.common.closeMenu}
        onClick={() => setMenuOpen(false)}
      />
      <aside className="sidebar" id="panel-navigation">
        <div className="sidebar-header">
          <Link href="/dashboard" className="brand">
            <span className="brand-mark-small">ک+</span>
            <span className="brand-copy">
              <strong>{dictionary.common.brand}</strong>
              <small>{dictionary.common.panel}</small>
            </span>
          </Link>
          <button
            type="button"
            className="icon-button sidebar-close"
            aria-label={dictionary.common.closeMenu}
            onClick={() => setMenuOpen(false)}
          >
            ×
          </button>
        </div>

        <nav className="sidebar-nav" aria-label={dictionary.nav.workspace}>
          <p className="nav-label">{dictionary.nav.workspace}</p>
          <NavLink
            href="/dashboard"
            label={dictionary.nav.overview}
            icon="dashboard"
            active={isActive("/dashboard")}
          />
          <NavLink
            href="/status"
            label={dictionary.nav.status}
            icon="pulse"
            active={isActive("/status")}
          />
          {user.permissions.includes("users:manage") ? (
            <NavLink
              href="/users"
              label={dictionary.nav.users}
              icon="grid"
              active={isActive("/users")}
            />
          ) : null}
          {user.permissions.includes("users:read") ? (
            <NavLink
              href="/app-users"
              label={dictionary.nav.appUsers}
              icon="grid"
              active={isActive("/app-users")}
            />
          ) : null}
          {user.permissions.includes("content:moderate") ? (
            <NavLink
              href="/reports"
              label={dictionary.nav.moderationReports}
              icon="grid"
              active={isActive("/reports")}
            />
          ) : null}

          <p className="nav-label nav-label-domains">
            {dictionary.nav.domains}
          </p>
          <div className="domain-navigation">
            {domainLinks.map(({ slug, label }) => (
              <NavLink
                key={slug}
                href={`/domains/${slug}`}
                label={label}
                icon="grid"
                active={pathname === `/domains/${slug}`}
              />
            ))}
          </div>
        </nav>

        <div className="sidebar-footer">
          <ProfileAvatar
            className="sidebar-avatar profile-image-avatar"
            image={user.profileImage}
            displayName={user.displayName}
            priority
          />
          <div className="sidebar-user-copy">
            <strong>{user.displayName}</strong>
            <small>{formatRole(user.roles[0] ?? "", locale)}</small>
          </div>
        </div>
      </aside>

      <div className="panel-main">
        <header className="topbar">
          <div className="topbar-leading">
            <button
              type="button"
              className="icon-button menu-button"
              aria-label={dictionary.common.openMenu}
              aria-controls="panel-navigation"
              aria-expanded={menuOpen}
              onClick={() => setMenuOpen(true)}
            >
              <span aria-hidden="true">☰</span>
            </button>
            <div className="topbar-title">
              <small>{dictionary.nav.workspace}</small>
              <strong>{dictionary.common.panel}</strong>
            </div>
          </div>
          <div className="topbar-actions">
            <LanguageSwitcher
              locale={locale}
              label={dictionary.common.changeLanguage}
            />
            <ThemeSwitcher
              initialTheme={theme}
              label={dictionary.common.changeTheme}
            />
            <form action={logout}>
              <button className="logout-button" type="submit">
                <span>{dictionary.common.logout}</span>
                <span aria-hidden="true">↪</span>
              </button>
            </form>
          </div>
        </header>
        <main className="content">{children}</main>
      </div>
    </div>
  );
}

function NavLink({
  href,
  label,
  active,
  icon,
}: {
  href: string;
  label: string;
  active: boolean;
  icon: "dashboard" | "pulse" | "grid";
}) {
  return (
    <Link
      href={href}
      className="nav-link"
      aria-current={active ? "page" : undefined}
    >
      <NavIcon icon={icon} />
      <span>{label}</span>
    </Link>
  );
}

function NavIcon({ icon }: { icon: "dashboard" | "pulse" | "grid" }) {
  if (icon === "dashboard")
    return (
      <svg viewBox="0 0 24 24" aria-hidden="true">
        <path d="M4 13h6V4H4v9Zm0 7h6v-5H4v5Zm10 0h6v-9h-6v9Zm0-16v5h6V4h-6Z" />
      </svg>
    );
  if (icon === "pulse")
    return (
      <svg viewBox="0 0 24 24" aria-hidden="true">
        <path
          d="M3 12h4l2-6 4 12 2-6h6"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    );
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true">
      <path d="M5 5h5v5H5V5Zm9 0h5v5h-5V5ZM5 14h5v5H5v-5Zm9 0h5v5h-5v-5Z" />
    </svg>
  );
}

const formatRole = (role: string, locale: Locale) => {
  const labels: Record<string, { fa: string; en: string }> = {
    super_admin: { fa: "مدیر ارشد", en: "Super admin" },
    admin: { fa: "مدیر", en: "Admin" },
    support: { fa: "پشتیبانی", en: "Support" },
  };
  return labels[role]?.[locale] ?? role.replaceAll("_", " ");
};
