"use client"

import { useTheme } from "next-themes"
import { Moon, Sun, Menu } from "lucide-react"
import { cn } from "@/lib/utils"
import { useEffect, useState } from "react"
import { useSidebar } from "@/contexts/sidebar-context"
import { useParams, usePathname } from "next/navigation"
import { PageBreadcrumb } from "./page-breadcrumb"

// Define all sections for breadcrumb lookup
const sections = [
  // Foundation
  { id: "color", name: "Color", category: "foundation" as const },
  { id: "iconography", name: "Iconography", category: "foundation" as const },
  { id: "typography", name: "Typography", category: "foundation" as const },
  { id: "spacing", name: "Spacing", category: "foundation" as const },
  { id: "elevation", name: "Elevation", category: "foundation" as const },

  // Components
  { id: "accordion", name: "Accordion", category: "components" as const },
  { id: "alerts", name: "Alert", category: "components" as const },
  { id: "alert-dialog", name: "Alert Dialog", category: "components" as const },
  { id: "avatars", name: "Avatar", category: "components" as const },
  { id: "badges", name: "Badge", category: "components" as const },
  { id: "breadcrumbs", name: "Breadcrumb", category: "components" as const },
  { id: "buttons", name: "Button", category: "components" as const },
  { id: "calendar", name: "Calendar", category: "components" as const },
  { id: "cards", name: "Card", category: "components" as const },
  { id: "checkbox", name: "Checkbox", category: "components" as const },
  { id: "collapsible", name: "Collapsible", category: "components" as const },
  { id: "combobox", name: "Combobox", category: "components" as const },
  { id: "command", name: "Command", category: "components" as const },
  { id: "context-menu", name: "Context Menu", category: "components" as const },
  { id: "dropdowns", name: "Dropdown", category: "components" as const },
  { id: "forms", name: "Form", category: "components" as const },
  { id: "hover-card", name: "Hover Card", category: "components" as const },
  { id: "label", name: "Label", category: "components" as const },
  { id: "modals", name: "Modal", category: "components" as const },
  { id: "pagination", name: "Pagination", category: "components" as const },
  { id: "progress", name: "Progress", category: "components" as const },
  { id: "scroll-area", name: "Scroll Area", category: "components" as const },
  { id: "sheet", name: "Sheet", category: "components" as const },
  { id: "skeleton", name: "Skeleton", category: "components" as const },
  { id: "slider", name: "Slider", category: "components" as const },
  { id: "switch", name: "Switch", category: "components" as const },
  { id: "tabs", name: "Tab", category: "components" as const },
  { id: "tables", name: "Table", category: "components" as const },
  { id: "toggle", name: "Toggle", category: "components" as const },
  { id: "tooltips", name: "Tooltip", category: "components" as const },

  // Blocks
  { id: "contact-form", name: "Contact Form", category: "blocks" as const },
  { id: "dashboard-stats", name: "Dashboard Stats", category: "blocks" as const },
  { id: "data-table", name: "Data Table", category: "blocks" as const },
  { id: "user-profile", name: "User Profile", category: "blocks" as const },
  { id: "settings-panel", name: "Settings Panel", category: "blocks" as const },
  { id: "file-upload", name: "File Upload", category: "blocks" as const },
]

export function FixedHeader() {
  const { setTheme, theme } = useTheme()
  const [mounted, setMounted] = useState(false)
  const { sidebarVisible, toggleSidebar } = useSidebar()
  const params = useParams()
  const pathname = usePathname()

  // Only show the theme toggle after mounting to avoid hydration mismatch
  useEffect(() => {
    setMounted(true)
  }, [])

  // Debug function to test toggle
  const handleToggleClick = () => {
    console.log("Toggle clicked, current state:", sidebarVisible)
    toggleSidebar()
  }

  // Determine if we should show breadcrumbs
  const shouldShowBreadcrumbs = () => {
    // Show breadcrumbs for section pages (like /buttons, /cards, etc.)
    if (params?.section && typeof params.section === "string") {
      const section = sections.find((s) => s.id === params.section)
      return !!section
    }

    // Show breadcrumbs for category pages
    if (pathname === "/foundation" || pathname === "/components" || pathname === "/blocks") {
      return true
    }

    return false
  }

  const getBreadcrumbData = () => {
    if (params?.section && typeof params.section === "string") {
      const section = sections.find((s) => s.id === params.section)
      if (section) {
        return {
          category: section.category,
          sectionName: section.name,
          sectionId: section.id,
        }
      }
    }

    // For category pages
    if (pathname === "/foundation") {
      return { category: "foundation" as const, sectionName: "Foundation", sectionId: "foundation" }
    }
    if (pathname === "/components") {
      return { category: "components" as const, sectionName: "Components", sectionId: "components" }
    }
    if (pathname === "/blocks") {
      return { category: "blocks" as const, sectionName: "Blocks", sectionId: "blocks" }
    }

    return null
  }

  const breadcrumbData = getBreadcrumbData()

  return (
    <header
      className="fixed top-0 z-[9999] h-16 transition-all duration-300 ease-in-out md:left-0 md:right-0"
      style={{
        // Mobile: full width
        left: typeof window !== "undefined" && window.innerWidth < 768 ? "0" : sidebarVisible ? "16rem" : "0",
        right: typeof window !== "undefined" && window.innerWidth < 768 ? "0" : "0",
      }}
    >
      {/* Single smooth progressive blur overlay */}
      <div
        className="absolute inset-0 pointer-events-none"
        style={{
          backdropFilter: "blur(40px)",
          maskImage: "linear-gradient(to top, transparent 0%, black 0%)",
          WebkitMaskImage: "linear-gradient(to top, transparent 0%, black 0%)",
        }}
      />

      {/* Container with content alignment matching page content */}
      <div className="relative w-full h-full flex items-center justify-between px-4 md:px-0">
        {/* Left side - Breadcrumbs aligned with page content */}
        <div className="flex items-center h-full">
          {/* Menu button - always visible on mobile, conditional on desktop */}
          <button
            onClick={handleToggleClick}
            className={`text-muted-foreground hover:text-foreground transition-colors flex items-center justify-center w-8 h-8 rounded-md hover:bg-background-secondary flex-shrink-0 ${!sidebarVisible ? "md:ml-6" : ""} md:${!sidebarVisible ? "flex" : "hidden"}`}
            aria-label="Show sidebar"
          >
            <Menu className="h-5 w-5" />
            <span className="sr-only">Show sidebar</span>
          </button>

          {/* Breadcrumbs - hidden on mobile, visible on desktop with proper spacing */}
          {shouldShowBreadcrumbs() && breadcrumbData && (
            <div className="hidden md:flex items-center justify-center h-full md:ml-6">
              <PageBreadcrumb
                category={breadcrumbData.category}
                sectionName={breadcrumbData.sectionName}
                sectionId={breadcrumbData.sectionId}
              />
            </div>
          )}
        </div>

        {/* Right side - Theme toggle */}
        <div className="flex items-center gap-3 h-full md:mr-4">
          {mounted && (
            <div className="flex h-8 items-center gap-1 border border-border px-1 bg-background/80 rounded-md backdrop-blur-sm">
              <button
                onClick={() => setTheme("light")}
                className={cn(
                  "h-6 w-6 flex items-center justify-center rounded",
                  theme === "light" ? "bg-[var(--background-secondary)] shadow-sm" : "bg-transparent",
                )}
                aria-label="Light mode"
              >
                <Sun className="h-4 w-4 text-foreground" />
              </button>
              <button
                onClick={() => setTheme("dark")}
                className={cn(
                  "h-6 w-6 flex items-center justify-center rounded",
                  theme === "dark" ? "bg-[var(--background-secondary)] shadow-sm" : "bg-transparent",
                )}
                aria-label="Dark mode"
              >
                <Moon className="h-4 w-4 text-foreground" />
              </button>
            </div>
          )}
        </div>
      </div>
    </header>
  )
}
