"use client";

import { useState, useCallback, useEffect, useRef } from "react";
import { usePathname, useRouter } from "next/navigation";
import { TopBar } from "@/components/layout/TopBar";
import { Sidebar } from "@/components/layout/Sidebar";
import { MainContent } from "@/components/layout/MainContent";
import { AppsProvider } from "@/components/providers/AppsProvider";
import { ToolsMenuProvider } from "@/components/providers/ToolsMenuProvider";
import { STORAGE_KEYS } from "@/lib/constants";

/**
 * Parse the URL pathname into navigation state.
 *
 * /                        → welcome
 * /chat                    → category: chat
 * /music                   → category: music
 * /status                  → category: status
 * /calendar                → category: calendar
 * /calendar/family         → category: calendar, subcategory: family
 * /skills/agent-skills     → category: skills, subcategory: agent-skills
 * /skills/mcp              → category: skills, subcategory: mcp
 * /apps/by-host            → category: apps, subcategory: by-host
 * /apps/by-host/123        → category: apps, subcategory: by-host:123
 * /apps/by-type/456        → category: apps, subcategory: by-type:456
 * /tools/type/abc          → category: tools, subcategory: type:abc
 * /agents/one              → agent: one
 * /administration/imessage → category: administration, subcategory: imessage
 */
function parsePathname(pathname: string) {
  const segments = pathname.split("/").filter(Boolean);
  let activeCategory: string | null = null;
  let activeAgent: string | null = null;
  let activeSubcategory: string | null = null;

  if (segments.length === 0) return { activeCategory, activeAgent, activeSubcategory };

  const root = segments[0];

  if (root === "agents" && segments[1]) {
    activeAgent = segments[1];
    activeCategory = "agents";
  } else if (root === "apps" && segments[1]) {
    activeCategory = "apps";
    if (segments[2]) {
      activeSubcategory = `${segments[1]}:${segments[2]}`;
    } else {
      activeSubcategory = segments[1];
    }
  } else if (root === "tools" && segments[1]) {
    activeCategory = "tools";
    if (segments[2]) {
      activeSubcategory = `${segments[1]}:${segments[2]}`;
    } else {
      activeSubcategory = segments[1];
    }
  } else if (segments[1]) {
    activeCategory = root;
    activeSubcategory = segments[1];
  } else {
    activeCategory = root;
  }

  return { activeCategory, activeAgent, activeSubcategory };
}

/**
 * Build a URL pathname from navigation state.
 */
function buildPathname(
  category: string | null,
  agent: string | null,
  subcategory: string | null,
): string {
  if (agent) return `/agents/${encodeURIComponent(agent)}`;
  if (!category) return "/";

  if (subcategory) {
    // Subcategories like "by-host:123" → /apps/by-host/123
    // Subcategories like "type:abc" → /tools/type/abc
    const colonIdx = subcategory.indexOf(":");
    if (colonIdx !== -1) {
      const prefix = subcategory.slice(0, colonIdx);
      const suffix = subcategory.slice(colonIdx + 1);
      return `/${category}/${prefix}/${encodeURIComponent(suffix)}`;
    }
    return `/${category}/${encodeURIComponent(subcategory)}`;
  }

  return `/${category}`;
}

function loadSavedNav(): { activeCategory: string | null; activeAgent: string | null; activeSubcategory: string | null } {
  try {
    const stored = localStorage.getItem(STORAGE_KEYS.ACTIVE_NAV);
    if (stored) return JSON.parse(stored);
  } catch {}
  return { activeCategory: null, activeAgent: null, activeSubcategory: null };
}

function saveNav(category: string | null, agent: string | null, subcategory: string | null) {
  try {
    localStorage.setItem(STORAGE_KEYS.ACTIVE_NAV, JSON.stringify({ activeCategory: category, activeAgent: agent, activeSubcategory: subcategory }));
  } catch {}
}

export default function Home() {
  const pathname = usePathname();
  const router = useRouter();
  const [sidebarOpen, setSidebarOpen] = useState(false);

  // Parse initial state from URL, falling back to localStorage if at root
  const initial = parsePathname(pathname);
  const [activeCategory, setActiveCategory] = useState<string | null>(initial.activeCategory);
  const [activeAgent, setActiveAgent] = useState<string | null>(initial.activeAgent);
  const [activeSubcategory, setActiveSubcategory] = useState<string | null>(initial.activeSubcategory);

  // Track whether this is the first run of the pathname sync effect.
  // On mount, state is already initialised from parsePathname(pathname) via useState
  // above, so we must skip the first sync to avoid overwriting the localStorage restore.
  const isFirstPathnameRun = useRef(true);
  // Skip the first save-on-change effect run to avoid clobbering localStorage before
  // the mount restore effect has had a chance to read it.
  const isFirstSaveRun = useRef(true);

  // On mount: if URL is root (/), restore saved nav from localStorage.
  // This runs before the pathname sync effect would clobber the restored state because
  // we skip the first run of the pathname sync (see isFirstPathnameRun below).
  useEffect(() => {
    if (pathname === "/") {
      const saved = loadSavedNav();
      if (saved.activeCategory || saved.activeAgent) {
        setActiveCategory(saved.activeCategory);
        setActiveAgent(saved.activeAgent);
        setActiveSubcategory(saved.activeSubcategory);
        const url = buildPathname(saved.activeCategory, saved.activeAgent, saved.activeSubcategory);
        if (url !== "/") router.replace(url);
      }
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Sync URL changes (e.g. browser back/forward) into state.
  // Skip the very first execution: useState already initialised from the URL, and
  // running here on mount would race with the localStorage restore above.
  useEffect(() => {
    if (isFirstPathnameRun.current) {
      isFirstPathnameRun.current = false;
      return;
    }
    const parsed = parsePathname(pathname);
    setActiveCategory(parsed.activeCategory);
    setActiveAgent(parsed.activeAgent);
    setActiveSubcategory(parsed.activeSubcategory);
  }, [pathname]);

  // Persist nav state to localStorage on every state change (e.g. browser back/forward).
  // Skip the very first run to avoid overwriting saved state before the restore effect reads it.
  useEffect(() => {
    if (isFirstSaveRun.current) {
      isFirstSaveRun.current = false;
      return;
    }
    saveNav(activeCategory, activeAgent, activeSubcategory);
  }, [activeCategory, activeAgent, activeSubcategory]);

  const navigate = useCallback(
    (category: string | null, agent: string | null, subcategory: string | null) => {
      setActiveCategory(category);
      setActiveAgent(agent);
      setActiveSubcategory(subcategory);
      saveNav(category, agent, subcategory);
      const url = buildPathname(category, agent, subcategory);
      router.push(url);
    },
    [router],
  );

  return (
    <AppsProvider>
    <ToolsMenuProvider>
    <div className="flex h-full flex-col">
      <TopBar onToggleSidebar={() => setSidebarOpen(!sidebarOpen)} />
      <div className="flex flex-1 overflow-hidden">
        <Sidebar
          open={sidebarOpen}
          onClose={() => setSidebarOpen(false)}
          activeCategory={activeCategory}
          onSelectCategory={(id) => {
            navigate(id, null, null);
            setSidebarOpen(false);
          }}
          activeAgent={activeAgent}
          onSelectAgent={(name) => {
            navigate("agents", name, null);
            setSidebarOpen(false);
          }}
          activeSubcategory={activeSubcategory}
          onSelectSubcategory={(sub, parentCategory) => {
            navigate(parentCategory, null, sub);
            setSidebarOpen(false);
          }}
        />
        <MainContent activeCategory={activeCategory} activeAgent={activeAgent} activeSubcategory={activeSubcategory} />
      </div>
    </div>
    </ToolsMenuProvider>
    </AppsProvider>
  );
}
