"use client"

import { useState, useEffect, useRef } from "react"
import { usePathname } from "next/navigation"
import Link from "next/link"
import { cn } from "@/lib/utils"
import { ChevronsLeft, Layers, Component, PanelTopIcon as PanelTopLeft, ChevronDown } from "lucide-react"
import { PercolateLogo } from "./ui/percolate-logo"
import { useSidebar } from "@/contexts/sidebar-context"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"

// Fixed border radius for UI components
const UI_BORDER_RADIUS = "6px"

// Add this function after the imports
const getElevation1Shadow = (theme: string) => {
  return theme === "dark" ? "0 1px 2px 0 rgba(0, 0, 0, 0.3)" : "0 1px 2px 0 rgba(0, 0, 0, 0.05)"
}

// Foundation items
const foundationItems = [
  { name: "Color", id: "color" },
  { name: "Iconography", id: "iconography" },
  { name: "Typography", id: "typography" },
  { name: "Spacing", id: "spacing" },
  { name: "Elevation", id: "elevation" },
]

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

// Block items - Updated to include AI Chat Interface
const blockItems = [
  { name: "AI Chat Interface", id: "ai-chat-interface" },
  { name: "Contact Form", id: "contact-form" },
  { name: "Data Table", id: "data-table" },
  { name: "User Profile", id: "user-profile" },
  { name: "Settings Panel", id: "settings-panel" },
  { name: "Login", id: "login" },
]

interface SidebarProps {
  isFirstLoad?: boolean
}

export function Sidebar({ isFirstLoad = false }: SidebarProps) {
  const pathname = usePathname()
  const [mounted, setMounted] = useState(false)
  const { setSidebarVisible } = useSidebar()
  const scrollContainerRef = useRef<HTMLDivElement>(null)

  const [openSections, setOpenSections] = useState({
    foundation: true,
    components: true,
    blocks: true,
  })

  const toggleSection = (section: string) => {
    setOpenSections((prev) => ({
      ...prev,
      [section]: !prev[section],
    }))
  }

  // Save scroll position to localStorage
  const saveScrollPosition = () => {
    if (scrollContainerRef.current) {
      const scrollTop = scrollContainerRef.current.scrollTop
      localStorage.setItem("sidebar-scroll-position", scrollTop.toString())
    }
  }

  // Restore scroll position from localStorage
  const restoreScrollPosition = () => {
    if (scrollContainerRef.current) {
      const savedScrollPosition = localStorage.getItem("sidebar-scroll-position")
      if (savedScrollPosition) {
        scrollContainerRef.current.scrollTop = Number.parseInt(savedScrollPosition, 10)
      }
    }
  }

  // Handle mounting and scroll position restoration
  useEffect(() => {
    setMounted(true)

    // Restore scroll position after a short delay to ensure DOM is ready
    const timer = setTimeout(() => {
      restoreScrollPosition()
    }, 100)

    return () => clearTimeout(timer)
  }, [])

  // Add scroll event listener to save position
  useEffect(() => {
    const scrollContainer = scrollContainerRef.current
    if (!scrollContainer) return

    const handleScroll = () => {
      saveScrollPosition()
    }

    // Throttle scroll events for better performance
    let timeoutId: NodeJS.Timeout
    const throttledHandleScroll = () => {
      clearTimeout(timeoutId)
      timeoutId = setTimeout(handleScroll, 100)
    }

    scrollContainer.addEventListener("scroll", throttledHandleScroll)

    return () => {
      scrollContainer.removeEventListener("scroll", throttledHandleScroll)
      clearTimeout(timeoutId)
    }
  }, [mounted])

  // Save scroll position when pathname changes
  useEffect(() => {
    saveScrollPosition()
  }, [pathname])

  if (!mounted) {
    return null
  }

  // Get current section from pathname
  const currentSection = pathname.replace("/", "") || "introduction"

  return (
    <div
      className="h-full"
      style={{
        backgroundColor: "var(--background-secondary)",
        borderRight: "0.5px solid hsl(var(--border))",
        boxSizing: "border-box",
        // Only animate content on first load
        animation:
          isFirstLoad && mounted ? "sidebarContentSlideIn 600ms cubic-bezier(0.23, 1, 0.32, 1) forwards" : "none",
        position: "relative", // Add position relative for absolute positioning inside
      }}
    >
      {/* Logo and toggle header */}
      <div className="h-16 flex items-center justify-between px-4">
        <Link
          href="/"
          className="font-semibold text-lg cursor-pointer hover:text-primary transition-colors flex items-center gap-2"
          style={{ color: "var(--text-primary)" }}
        >
          <PercolateLogo />
          <span>percolate UI</span>
        </Link>

        <button
          onClick={() => setSidebarVisible(false)}
          className="text-muted-foreground hover:text-foreground transition-colors flex items-center justify-center w-8 h-8 rounded-md hover:bg-background-secondary"
          title="Hide sidebar"
        >
          <ChevronsLeft className="h-5 w-5" />
          <span className="sr-only">Hide sidebar</span>
        </button>
      </div>

      {/* Scrollable content area that fills the entire height */}
      <div ref={scrollContainerRef} className="h-[calc(100%-4rem)] overflow-y-auto">
        <div className="p-4 pt-6">
          {/* Introduction section */}
          <div className="mb-6">
            <Link href="/">
              <button
                className={cn(
                  "flex items-center px-3 py-1 text-sm w-full text-left rounded",
                  currentSection === "introduction" ? "text-foreground font-medium" : "hover:text-foreground",
                )}
                style={{
                  borderRadius: UI_BORDER_RADIUS,
                  backgroundColor: currentSection === "introduction" ? "var(--background-primary)" : undefined,
                  boxShadow: currentSection === "introduction" ? "0 1px 2px 0 rgba(0, 0, 0, 0.05)" : undefined,
                  color: currentSection === "introduction" ? undefined : "var(--text-primary)",
                }}
                onMouseEnter={(e) => {
                  if (currentSection !== "introduction") {
                    e.currentTarget.style.backgroundColor = "var(--background-primary)"
                  }
                }}
                onMouseLeave={(e) => {
                  if (currentSection !== "introduction") {
                    e.currentTarget.style.backgroundColor = ""
                  }
                }}
              >
                Introduction
              </button>
            </Link>
          </div>

          {/* Foundation section */}
          <Collapsible open={openSections.foundation} onOpenChange={() => toggleSection("foundation")}>
            <CollapsibleTrigger
              className="flex items-center justify-between w-full text-xs font-medium mb-1 px-2 hover:text-foreground transition-colors"
              style={{ color: "var(--text-primary)" }}
            >
              <div className="flex items-center gap-2">
                <Layers className="h-3 w-3" />
                FOUNDATION
              </div>
              <ChevronDown className={`h-3 w-3 transition-transform ${openSections.foundation ? "rotate-180" : ""}`} />
            </CollapsibleTrigger>
            <CollapsibleContent>
              <nav
                className="mb-4 ml-5"
                style={{ overflow: "visible", display: "flex", flexDirection: "column", gap: "0.25rem" }}
              >
                {foundationItems.map((item) => (
                  <Link key={item.id} href={`/${item.id}`}>
                    <button
                      className={cn(
                        "flex items-center px-3 py-1 text-sm w-full text-left rounded",
                        currentSection === item.id ? "text-foreground font-medium" : "hover:text-foreground",
                      )}
                      style={{
                        borderRadius: UI_BORDER_RADIUS,
                        backgroundColor: currentSection === item.id ? "var(--background-primary)" : undefined,
                        boxShadow: currentSection === item.id ? "0 1px 2px 0 rgba(0, 0, 0, 0.05)" : undefined,
                        color: currentSection === item.id ? undefined : "var(--text-primary)",
                      }}
                      onMouseEnter={(e) => {
                        if (currentSection !== item.id) {
                          e.currentTarget.style.backgroundColor = "var(--background-primary)"
                        }
                      }}
                      onMouseLeave={(e) => {
                        if (currentSection !== item.id) {
                          e.currentTarget.style.backgroundColor = ""
                        }
                      }}
                    >
                      {item.name}
                    </button>
                  </Link>
                ))}
              </nav>
            </CollapsibleContent>
          </Collapsible>

          {/* Components section */}
          <Collapsible open={openSections.components} onOpenChange={() => toggleSection("components")}>
            <CollapsibleTrigger
              className="flex items-center justify-between w-full text-xs font-medium mb-1 px-2 mt-6 hover:text-foreground transition-colors"
              style={{ color: "var(--text-primary)" }}
            >
              <div className="flex items-center gap-2">
                <Component className="h-3 w-3" />
                COMPONENTS
              </div>
              <ChevronDown className={`h-3 w-3 transition-transform ${openSections.components ? "rotate-180" : ""}`} />
            </CollapsibleTrigger>
            <CollapsibleContent>
              <nav
                className="ml-5"
                style={{ overflow: "visible", display: "flex", flexDirection: "column", gap: "0.25rem" }}
              >
                {componentItems.map((item) => (
                  <Link key={item.id} href={`/${item.id}`}>
                    <button
                      className={cn(
                        "flex items-center px-3 py-1 text-sm w-full text-left rounded",
                        currentSection === item.id ? "text-foreground font-medium" : "hover:text-foreground",
                      )}
                      style={{
                        borderRadius: UI_BORDER_RADIUS,
                        backgroundColor: currentSection === item.id ? "var(--background-primary)" : undefined,
                        boxShadow: currentSection === item.id ? "0 1px 2px 0 rgba(0, 0, 0, 0.05)" : undefined,
                        color: currentSection === item.id ? undefined : "var(--text-primary)",
                      }}
                      onMouseEnter={(e) => {
                        if (currentSection !== item.id) {
                          e.currentTarget.style.backgroundColor = "var(--background-primary)"
                        }
                      }}
                      onMouseLeave={(e) => {
                        if (currentSection !== item.id) {
                          e.currentTarget.style.backgroundColor = ""
                        }
                      }}
                    >
                      {item.name}
                    </button>
                  </Link>
                ))}
              </nav>
            </CollapsibleContent>
          </Collapsible>

          {/* Blocks section */}
          {blockItems.length > 0 && (
            <Collapsible open={openSections.blocks} onOpenChange={() => toggleSection("blocks")}>
              <CollapsibleTrigger
                className="flex items-center justify-between w-full text-xs font-medium mb-1 px-2 mt-6 hover:text-foreground transition-colors"
                style={{ color: "var(--text-primary)" }}
              >
                <div className="flex items-center gap-2">
                  <PanelTopLeft className="h-3 w-3" />
                  BLOCKS
                </div>
                <ChevronDown className={`h-3 w-3 transition-transform ${openSections.blocks ? "rotate-180" : ""}`} />
              </CollapsibleTrigger>
              <CollapsibleContent>
                <nav
                  className="ml-5"
                  style={{ overflow: "visible", display: "flex", flexDirection: "column", gap: "0.25rem" }}
                >
                  {blockItems.map((item) => (
                    <Link key={item.id} href={`/${item.id}`}>
                      <button
                        className={cn(
                          "flex items-center px-3 py-1 text-sm w-full text-left rounded",
                          currentSection === item.id ? "text-foreground font-medium" : "hover:text-foreground",
                        )}
                        style={{
                          borderRadius: UI_BORDER_RADIUS,
                          backgroundColor: currentSection === item.id ? "var(--background-primary)" : undefined,
                          boxShadow: currentSection === item.id ? "0 1px 2px 0 rgba(0, 0, 0, 0.05)" : undefined,
                          color: currentSection === item.id ? undefined : "var(--text-primary)",
                        }}
                        onMouseEnter={(e) => {
                          if (currentSection !== item.id) {
                            e.currentTarget.style.backgroundColor = "var(--background-primary)"
                          }
                        }}
                        onMouseLeave={(e) => {
                          if (currentSection !== item.id) {
                            e.currentTarget.style.backgroundColor = ""
                          }
                        }}
                      >
                        {item.name}
                      </button>
                    </Link>
                  ))}
                </nav>
              </CollapsibleContent>
            </Collapsible>
          )}
        </div>
      </div>
    </div>
  )
}
