import React, { useEffect, useState } from "react";
import { iconDataUri } from "../icons/iconData";
import { popQueuedAdminToast, subscribeAdminToast } from "../utils/adminToast";

const PAGE_CONTEXT = {
  pointlybooking_dashboard: {
    eyebrow: "Overview",
    title: "Dashboard workspace",
    subtitle: "Track bookings, services, staff activity, and booking performance.",
  },
  pointlybooking_bookings: {
    eyebrow: "Operations",
    title: "Bookings workspace",
    subtitle: "Review appointments, update statuses, and keep the calendar moving.",
  },
  pointlybooking_bookings_edit: {
    eyebrow: "Operations",
    title: "Booking editor",
    subtitle: "Create or update a booking with service, customer, and schedule details.",
  },
  pointlybooking_calendar: {
    eyebrow: "Planning",
    title: "Calendar workspace",
    subtitle: "Scan bookings, capacity, and daily scheduling at a glance.",
  },
  pointlybooking_services: {
    eyebrow: "Catalog",
    title: "Services workspace",
    subtitle: "Manage service cards, pricing, and availability-building blocks.",
  },
  pointlybooking_services_edit: {
    eyebrow: "Catalog",
    title: "Service editor",
    subtitle: "Adjust service details, pricing, duration, and category assignments.",
  },
  pointlybooking_categories: {
    eyebrow: "Catalog",
    title: "Categories workspace",
    subtitle: "Organize services into cleaner booking paths for customers.",
  },
  pointlybooking_categories_edit: {
    eyebrow: "Catalog",
    title: "Category editor",
    subtitle: "Update category labels, display order, and supporting content.",
  },
  pointlybooking_extras: {
    eyebrow: "Catalog",
    title: "Extras workspace",
    subtitle: "Shape upsells and optional add-ons in the booking flow.",
  },
  pointlybooking_extras_edit: {
    eyebrow: "Catalog",
    title: "Extra editor",
    subtitle: "Edit add-on details, pricing, and service availability.",
  },
  pointlybooking_locations: {
    eyebrow: "Scheduling",
    title: "Locations workspace",
    subtitle: "Manage where services run and how location choices appear.",
  },
  pointlybooking_locations_edit: {
    eyebrow: "Scheduling",
    title: "Location editor",
    subtitle: "Update location details, business info, and operational settings.",
  },
  pointlybooking_location_categories_edit: {
    eyebrow: "Scheduling",
    title: "Location categories",
    subtitle: "Control which service groups appear within each location.",
  },
  pointlybooking_agents: {
    eyebrow: "Team",
    title: "Agents workspace",
    subtitle: "Manage staff records, visibility, and service coverage.",
  },
  pointlybooking_agents_edit: {
    eyebrow: "Team",
    title: "Agent editor",
    subtitle: "Update staff details, schedules, and assigned services.",
  },
  pointlybooking_customers: {
    eyebrow: "CRM",
    title: "Customers workspace",
    subtitle: "Review customer records, booking history, and contact details.",
  },
  pointlybooking_customers_edit: {
    eyebrow: "CRM",
    title: "Customer editor",
    subtitle: "Update customer details and keep profile information consistent.",
  },
  pointlybooking_settings: {
    eyebrow: "Configuration",
    title: "Settings workspace",
    subtitle: "Tune booking rules, business defaults, and payment behavior.",
  },
  pointlybooking_settings_payments: {
    eyebrow: "Configuration",
    title: "Payments workspace",
    subtitle: "Configure payment gateways, checkout defaults, and payment behavior.",
  },
  pointlybooking_schedule: {
    eyebrow: "Configuration",
    title: "Schedule workspace",
    subtitle: "Set working hours, breaks, timezone defaults, and booking cadence.",
  },
  pointlybooking_holidays: {
    eyebrow: "Configuration",
    title: "Holidays workspace",
    subtitle: "Manage company-wide closures and agent-specific time off.",
  },
  pointlybooking_form_fields: {
    eyebrow: "Configuration",
    title: "Form fields workspace",
    subtitle: "Control the custom fields shown through the booking experience.",
  },
  pointlybooking_notifications: {
    eyebrow: "Automation",
    title: "Workflow workspace",
    subtitle: "Manage email, reminders, triggers, and workflow actions.",
  },
  pointlybooking_design_form: {
    eyebrow: "Experience",
    title: "Booking form designer",
    subtitle: "Refine the public booking flow layout, steps, and presentation.",
  },
  pointlybooking_how_to_use: {
    eyebrow: "Guides",
    title: "How-to workspace",
    subtitle: "Review usage notes, setup guidance, and practical walkthroughs.",
  },
  pointlybooking_pro: {
    eyebrow: "Upgrade",
    title: "Pro center",
    subtitle: "Review premium capabilities, setup paths, and upgrade options.",
  },
  pointlybooking_promo_codes: {
    eyebrow: "Revenue",
    title: "Promo codes workspace",
    subtitle: "Create and manage discount rules for bookings and campaigns.",
  },
  pointlybooking_tools: {
    eyebrow: "Maintenance",
    title: "Tools workspace",
    subtitle: "Run diagnostics, imports, exports, and maintenance tasks.",
  },
  pointlybooking_audit: {
    eyebrow: "Logs",
    title: "Audit workspace",
    subtitle: "Inspect booking activity, history, and operational changes.",
  },
};

const SETTINGS_TAB_PAGE_MAP = {
  general: "pointlybooking_settings",
  payments: "pointlybooking_settings_payments",
  schedule: "pointlybooking_schedule",
  holidays: "pointlybooking_holidays",
  form_fields: "pointlybooking_form_fields",
  promo_codes: "pointlybooking_promo_codes",
  notifications: "pointlybooking_notifications",
  audit_log: "pointlybooking_audit",
  tools: "pointlybooking_tools",
};

function humanizePage(page) {
  const normalized = String(page || "")
    .replace(/^pointlybooking_/, "")
    .replace(/_/g, " ")
    .trim();
  if (!normalized) return "BookPoint workspace";
  return normalized.replace(/\b\w/g, (match) => match.toUpperCase());
}

export default function Shell({ theme, onToggleTheme, active, children }) {
  const page = window.pointlybooking_ADMIN?.page || "pointlybooking_dashboard";
  const settingsTab = new URLSearchParams(window.location.search).get("tab") || "general";
  const resolvedPage = page === "pointlybooking_settings" ? SETTINGS_TAB_PAGE_MAP[settingsTab] || page : page;
  const proActive = Boolean(window.pointlybooking_ADMIN?.proActive);
  const pluginUrl = String(window.pointlybooking_ADMIN?.pluginUrl || window.bpAdmin?.pluginUrl || "").replace(/\/$/, "");
  const publicImagesUrl = (
    window.pointlybooking_ADMIN?.publicImagesUrl ||
    window.bpAdmin?.publicImagesUrl ||
    (pluginUrl ? `${pluginUrl}/public/images` : "")
  ).replace(/\/$/, "");
  const build = window.pointlybooking_ADMIN?.build || Date.now();
  const logoBase = publicImagesUrl ? `${publicImagesUrl}/logo.png` : "";
  const logoUrl = logoBase ? `${logoBase}?v=${encodeURIComponent(build)}` : "";
  const wpLogoBase = publicImagesUrl ? `${publicImagesUrl}/wordpress-logo.png` : "";
  const wpLogoUrl = wpLogoBase ? `${wpLogoBase}?v=${encodeURIComponent(build)}` : "";
  const ICON = (name, isActive = false) => iconDataUri(name, { active: isActive, theme });

  const [isDesktopSidebar, setIsDesktopSidebar] = useState(() => window.innerWidth >= 640);
  const [collapsed, setCollapsed] = useState(() => {
    try {
      return window.innerWidth >= 640 && window.localStorage.getItem("pointlybooking_sidebar_collapsed") === "1";
    } catch (e) {
      return false;
    }
  });
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [queuedToast, setQueuedToast] = useState(null);

  const pickIcon = (name, isActive) => ICON(name, isActive);
  const is = (p) => {
    if (resolvedPage === p) return true;
    if (p === "pointlybooking_locations" && (page === "pointlybooking_locations_edit" || page === "pointlybooking_location_categories_edit")) return true;
    if (p === "pointlybooking_bookings" && page === "pointlybooking_bookings_edit") return true;
    if (p === "pointlybooking_services" && page === "pointlybooking_services_edit") return true;
    if (p === "pointlybooking_categories" && page === "pointlybooking_categories_edit") return true;
    if (p === "pointlybooking_extras" && page === "pointlybooking_extras_edit") return true;
    if (p === "pointlybooking_agents" && page === "pointlybooking_agents_edit") return true;
    if (p === "pointlybooking_customers" && page === "pointlybooking_customers_edit") return true;
    return false;
  };

  useEffect(() => {
    try {
      window.localStorage.setItem("pointlybooking_sidebar_collapsed", collapsed ? "1" : "0");
    } catch (e) {
      // ignore storage failures
    }
  }, [collapsed]);

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") setSidebarOpen(false);
    };
    const onResize = () => {
      const isDesktop = window.innerWidth >= 640;
      setIsDesktopSidebar(isDesktop);
      if (isDesktop) {
        setSidebarOpen(false);
      }
    };
    window.addEventListener("keydown", onKey);
    window.addEventListener("resize", onResize);
    return () => {
      window.removeEventListener("keydown", onKey);
      window.removeEventListener("resize", onResize);
    };
  }, []);

  useEffect(() => {
    const toast = popQueuedAdminToast();
    if (toast) {
      setQueuedToast(toast);
    }
    return subscribeAdminToast((nextToast) => {
      setQueuedToast(nextToast);
    });
  }, []);

  useEffect(() => {
    if (!queuedToast) return undefined;
    const timeout = window.setTimeout(() => setQueuedToast(null), queuedToast.duration || 2600);
    return () => window.clearTimeout(timeout);
  }, [queuedToast]);

  const iconMenu = ICON("menu", false);
  const settingsShellActive = [
    "pointlybooking_settings",
    "pointlybooking_settings_payments",
    "pointlybooking_schedule",
    "pointlybooking_holidays",
    "pointlybooking_form_fields",
    "pointlybooking_promo_codes",
    "pointlybooking_notifications",
    "pointlybooking_audit",
    "pointlybooking_tools",
  ].includes(resolvedPage);
  const iconCalendar = pickIcon("calendar", is("pointlybooking_calendar"));
  const iconSettings = pickIcon("settings", settingsShellActive);
  const iconAdmin = pickIcon("customers", is("pointlybooking_customers"));
  const proLabel = proActive ? "BookPoint Pro" : "Upgrade to Pro";
  const proItemClass = `bp-nav-item ${is("pointlybooking_pro") ? "active" : ""} ${proActive ? "" : "bp-nav-upgrade"}`.trim();
  const topbarContext = PAGE_CONTEXT[resolvedPage] || PAGE_CONTEXT[page] || {
    eyebrow: "Workspace",
    title: humanizePage(resolvedPage),
    subtitle: "Manage this area using the controls and filters available on the page below.",
  };
  const sidebarCollapsed = collapsed && isDesktopSidebar;
  const shellStatusLabel = proActive ? "Pro active" : "Core plugin";
  const shellStatusShort = proActive ? "Pro" : "Core";
  const navGroups = [
    {
      title: "Core",
      items: [
        { key: "pointlybooking_dashboard", label: "Dashboard", icon: "dashboard", href: "admin.php?page=pointlybooking_dashboard" },
        { key: "pointlybooking_bookings", label: "Bookings", icon: "bookings", href: "admin.php?page=pointlybooking_bookings" },
        { key: "pointlybooking_calendar", label: "Calendar", icon: "calendar", href: "admin.php?page=pointlybooking_calendar" },
      ],
    },
    {
      title: "Catalog",
      items: [
        { key: "pointlybooking_services", label: "Services", icon: "services", href: "admin.php?page=pointlybooking_services" },
        { key: "pointlybooking_categories", label: "Categories", icon: "categories", href: "admin.php?page=pointlybooking_categories" },
        { key: "pointlybooking_extras", label: "Service Extras", icon: "service-extras", href: "admin.php?page=pointlybooking_extras" },
        { key: "pointlybooking_locations", label: "Locations", icon: "locations", href: "admin.php?page=pointlybooking_locations" },
      ],
    },
    {
      title: "People",
      items: [
        { key: "pointlybooking_agents", label: "Agents", icon: "agents", href: "admin.php?page=pointlybooking_agents" },
        { key: "pointlybooking_customers", label: "Customers", icon: "customers", href: "admin.php?page=pointlybooking_customers" },
      ],
    },
    {
      title: "Growth",
      items: [
        { key: "pointlybooking_promo_codes", label: "Promo Codes", icon: "service-extras", href: "admin.php?page=pointlybooking_settings&tab=promo_codes" },
        { key: "pointlybooking_notifications", label: "Automation", icon: "settings", href: "admin.php?page=pointlybooking_settings&tab=notifications" },
        { key: "pointlybooking_design_form", label: "Booking Form Designer", icon: "designer", href: "admin.php?page=pointlybooking_design_form" },
      ],
    },
    {
      title: "System",
      items: [
        { key: "pointlybooking_settings", label: "Settings", icon: "settings", href: "admin.php?page=pointlybooking_settings" },
        { key: "pointlybooking_audit", label: "Audit Log", icon: "settings", href: "admin.php?page=pointlybooking_settings&tab=audit_log" },
        { key: "pointlybooking_tools", label: "Tools", icon: "settings", href: "admin.php?page=pointlybooking_settings&tab=tools" },
      ],
    },
    {
      title: "Support",
      items: [
        { key: "pointlybooking_how_to_use", label: "How to Use", icon: "settings", href: "admin.php?page=pointlybooking_how_to_use" },
        { key: "pointlybooking_pro", label: proLabel, icon: "pro", href: "admin.php?page=pointlybooking_pro", isUpgrade: !proActive },
      ],
    },
  ];

  return (
    <div className="bp-app">
      <div className="bp-shell">
        <aside className={`bp-sidebar ${sidebarCollapsed ? "is-collapsed" : ""} ${sidebarOpen ? "is-open" : ""}`}>
          <div className="bp-brand">
            <div className="bp-logo">
              <img src={logoUrl} alt="BookPoint" />
            </div>
            <div>
              <div className="bp-title">BookPoint</div>
              <div className="bp-sub">Admin</div>
            </div>
            <button
              type="button"
              className="bp-sidebar-close"
              onClick={() => setSidebarOpen(false)}
              aria-label="Close menu"
            >
              X
            </button>
            <button
              type="button"
              className="bp-sidebar-toggle"
              onClick={() => setCollapsed((v) => !v)}
              aria-label="Toggle sidebar"
            >
              <img src={iconMenu} alt="" />
            </button>
          </div>

          <div className="bp-nav-wrap">
            <nav className="bp-nav">
              {navGroups.map((group, groupIndex) => (
                <div key={group.title} className="bp-sidegroup">
                  <div className={`bp-group-title ${groupIndex === 0 ? "is-first" : ""}`}>{group.title}</div>
                  {group.items.map((item) => {
                    const activeItem = is(item.key);
                    const itemClass = `bp-nav-item ${activeItem ? "active" : ""} ${item.isUpgrade ? "bp-nav-upgrade" : ""}`.trim();
                    return (
                      <a
                        key={item.key}
                        className={item.isUpgrade ? proItemClass : itemClass}
                        href={item.href}
                        aria-current={activeItem ? "page" : undefined}
                      >
                        <span className="bp-sidebar-item" title={sidebarCollapsed ? item.label : ""}>
                          <img className="bp-sidebar-icon" src={pickIcon(item.icon, activeItem)} alt="" aria-hidden="true" />
                          <span className="bp-sidebar-text">{item.label}</span>
                          {item.isUpgrade && !proActive ? <span className="bp-nav-upgrade-tag">PRO</span> : null}
                          {item.isUpgrade && !proActive ? <span className="bp-upgrade-dot" aria-hidden="true" /> : null}
                        </span>
                      </a>
                    );
                  })}
                </div>
              ))}
            </nav>
          </div>

          <div className="bp-sidebar-footer">
            <div className={`bp-sidebar-status ${proActive ? "is-pro" : "is-core"}`}>{shellStatusLabel}</div>
            <a className="bp-wp-link" href="index.php" aria-label="Back to WordPress">
              <img src={wpLogoUrl} alt="" aria-hidden="true" />
              <span className="bp-wp-link__label">Back to WordPress</span>
            </a>
          </div>
        </aside>

        <div
          className={`bp-sidebar-overlay ${sidebarOpen ? "is-open" : ""}`}
          onClick={() => setSidebarOpen(false)}
          aria-hidden={!sidebarOpen}
        />

        <main className="bp-main">
          {queuedToast ? (
            <div
              className={`bp-toast ${queuedToast.type === "error" ? "bp-alert bp-alert-error" : "bp-toast-success"} bp-toast-global`}
              role={queuedToast.type === "error" ? "alert" : "status"}
              aria-live={queuedToast.type === "error" ? "assertive" : "polite"}
            >
              {queuedToast.message}
            </div>
          ) : null}

          <header className="bp-topbar">
            <div className="bp-topbar__left">
              <button
                type="button"
                className="bp-topbar__menu"
                onClick={() => {
                  if (isDesktopSidebar) {
                    setCollapsed((v) => !v);
                  } else {
                    setSidebarOpen((v) => !v);
                  }
                }}
                aria-label="Toggle menu"
              >
                <img src={iconMenu} alt="" />
              </button>
              <div className="bp-topbar__logo">
                <img src={logoUrl} alt="BookPoint" />
              </div>
            </div>

            <div className="bp-topbar__center">
              <div className="bp-topbar-context" aria-label="Current workspace">
                <div className="bp-topbar-context__eyebrow">{topbarContext.eyebrow}</div>
                <div className="bp-topbar-context__title">{topbarContext.title}</div>
                <div className="bp-topbar-context__sub">{topbarContext.subtitle}</div>
              </div>
            </div>

            <div className="bp-topbar__right">
              <div className="bp-topbar__dock">
                <a className={`bp-icon-btn ${is("pointlybooking_calendar") ? "is-active" : ""}`} href="admin.php?page=pointlybooking_calendar" aria-label="Calendar" aria-current={is("pointlybooking_calendar") ? "page" : undefined}>
                  <img src={iconCalendar} alt="" />
                </a>
                <a className={`bp-icon-btn ${settingsShellActive ? "is-active" : ""}`} href="admin.php?page=pointlybooking_settings" aria-label="Settings" aria-current={settingsShellActive ? "page" : undefined}>
                  <img src={iconSettings} alt="" />
                </a>
                <a className={`bp-icon-btn ${is("pointlybooking_customers") ? "is-active" : ""}`} href="admin.php?page=pointlybooking_customers" aria-label="Customers" aria-current={is("pointlybooking_customers") ? "page" : undefined}>
                  <img src={iconAdmin} alt="" />
                </a>
              </div>

              <a className="bp-primary-btn bp-topbar__cta" href="admin.php?page=pointlybooking_bookings_edit&new=1">
                + Booking
              </a>
              <div className={`bp-topbar-badge ${proActive ? "is-pro" : "is-core"}`}>{shellStatusShort}</div>
            </div>
          </header>

          <div className="bp-content">{children}</div>
        </main>
      </div>
    </div>
  );
}
