import { type ParentProps, createMemo, createSignal, onMount } from "solid-js";
import { useLocation, useNavigate } from "@solidjs/router";
import DashboardShell from "~/components/DashboardShell";

const SIDEBAR_ITEMS = [
  "My Dashboard",
  "Leads",
  "My Requests",
  "Credits",
  "Settings",
  "Logout",
];

const ROUTE_BY_LABEL: Record<string, string> = {
  "my dashboard": "/dashboard",
  leads: "/dashboard/leads",
  "my requests": "/dashboard/requests",
  credits: "/dashboard/credits",
  settings: "/dashboard/settings",
  logout: "/dashboard/logout",
};

function readUserName() {
  if (typeof window === "undefined") return "User";
  try {
    const raw =
      sessionStorage.getItem("nxtgauge_auth_user") ||
      sessionStorage.getItem("nxtgauge_user") ||
      localStorage.getItem("nxtgauge_auth_user") ||
      localStorage.getItem("nxtgauge_user");
    if (!raw) return "User";
    const parsed = JSON.parse(raw);
    return parsed?.full_name || parsed?.name || parsed?.email || "User";
  } catch {
    return "User";
  }
}

export default function DashboardLayout(props: ParentProps) {
  const location = useLocation();
  const navigate = useNavigate();
  const [roleKey, setRoleKey] = createSignal("DEVELOPER");
  const [userName, setUserName] = createSignal("User");

  const activeSidebar = createMemo(() => {
    const path = location.pathname || "";
    if (path.startsWith("/dashboard/requests")) return "My Requests";
    if (path.startsWith("/dashboard/leads")) return "Leads";
    if (path.startsWith("/dashboard/credits")) return "Credits";
    if (path.startsWith("/dashboard/settings")) return "Settings";
    return "My Dashboard";
  });

  const handleSidebarSelect = (item: string) => {
    const target = ROUTE_BY_LABEL[item.toLowerCase()];
    if (target) navigate(target);
  };

  onMount(async () => {
    if (typeof window === "undefined") return;

    const fromUrl = new URLSearchParams(window.location.search).get("role");
    if (fromUrl && fromUrl.trim()) {
      setRoleKey(fromUrl.trim().toUpperCase());
      return;
    }

    const storageKeys = [
      ["nxtgauge_signup_profile_v1", localStorage],
      ["nxtgauge_auth_user", localStorage],
      ["nxtgauge_user", localStorage],
      ["nxtgauge_signup_profile_v1", sessionStorage],
      ["nxtgauge_auth_user", sessionStorage],
      ["nxtgauge_user", sessionStorage],
    ];

    for (const [key, storage] of storageKeys) {
      try {
        const raw = storage.getItem(key);
        if (raw) {
          const parsed = JSON.parse(raw);
          const candidate = String(
            parsed?.selectedProfessionalRole || parsed?.active_role || parsed?.roleKey || parsed?.role || ""
          )
            .trim()
            .toUpperCase();
          if (candidate && candidate !== "PROFESSIONAL") {
            setRoleKey(candidate);
            if (parsed?.full_name || parsed?.name || parsed?.email) {
              setUserName(parsed.full_name || parsed.name || parsed.email || "User");
            }
            return;
          }
        }
      } catch {
        // continue
      }
    }

    const token = sessionStorage.getItem("nxtgauge_access_token");
    if (token) {
      try {
        const res = await fetch("/api/auth/session", {
          headers: {
            Accept: "application/json",
            Authorization: `Bearer ${token}`,
          },
          credentials: "include",
        });
        if (res.ok) {
          const data = await res.json();
          const role = String(data?.active_role || data?.role || "").trim().toUpperCase();
          setRoleKey(role && role !== "PROFESSIONAL" ? role : "DEVELOPER");
          setUserName(data?.full_name || data?.name || data?.email || "User");
          return;
        }
      } catch {
        // fall through
      }
    }
  });

  return (
    <DashboardShell
      sidebarItems={SIDEBAR_ITEMS}
      activeSidebar={activeSidebar()}
      onSidebarSelect={handleSidebarSelect}
      roleKey={roleKey()}
      userName={userName()}
    >
      {props.children}
    </DashboardShell>
  );
}
