"use client"

import React from "react"

import type { ReactNode } from "react"
import { useRef, useLayoutEffect, useEffect } from "react"
import { cn } from "@/lib/utils"
import { useView } from "@/contexts/view-context"
import { useSidebar } from "@/contexts/sidebar-context"
import { ColorSection } from "@/components/sections/color-section"
import { TypographySection } from "@/components/sections/typography-section"
import { AdvancedTypographySection } from "@/components/sections/advanced-typography-section"
import { SpacingSection } from "@/components/sections/spacing-section"
import { ButtonsSection } from "@/components/sections/buttons-section"
import { CardsSection } from "@/components/sections/cards-section"
import { FormsSection } from "@/components/sections/forms-section"
import { AlertsSection } from "@/components/sections/alerts-section"
import { AvatarsSection } from "@/components/sections/avatars-section"
import { BadgesSection } from "@/components/sections/badges-section"
import { BreadcrumbsSection } from "@/components/sections/breadcrumbs-section"
import { DropdownsSection } from "@/components/sections/dropdowns-section"
import { ModalsSection } from "@/components/sections/modals-section"
import { PaginationSection } from "@/components/sections/pagination-section"
import { ProgressSection } from "@/components/sections/progress-section"
import { TabsSection } from "@/components/sections/tabs-section"
import { TooltipsSection } from "@/components/sections/tooltips-section"
import { ToggleSection } from "@/components/sections/toggle-section"
import { TablesSection } from "@/components/sections/tables-section"
import { AccordionSection } from "@/components/sections/accordion-section"
import { SliderSection } from "@/components/sections/slider-section"
import { SkeletonSection } from "@/components/sections/skeleton-section"
import { IconographySection } from "@/components/sections/iconography-section"
import { CalendarSection } from "@/components/sections/calendar-section"
import { CascadedComponentDemo } from "@/components/cascaded-component-demo"
import { useMaterial } from "@/contexts/material-context"
import { Separator } from "@/components/ui/separator"

// Import the new component sections
import { AlertDialogSection } from "@/components/sections/alert-dialog-section"
import { CheckboxSection } from "@/components/sections/checkbox-section"
import { CollapsibleSection } from "@/components/sections/collapsible-section"
import { ContextMenuSection } from "@/components/sections/context-menu-section"
import { ElevationSection } from "@/components/sections/elevation-section"
import { ContactFormSection } from "@/components/sections/contact-form-section"
import { HoverCardSection } from "@/components/sections/hover-card-section"
import { ScrollAreaSection } from "@/components/sections/scroll-area-section"
import { SheetSection } from "@/components/sections/sheet-section"
import { ComboboxSection } from "@/components/sections/combobox-section"
import { LabelSection } from "@/components/sections/label-section"

// Import the new sections
import { DashboardStatsSection } from "@/components/sections/dashboard-stats-section"
import { DataTableSection } from "@/components/sections/data-table-section"
import { UserProfileSection } from "@/components/sections/user-profile-section"
import { SettingsPanelSection } from "@/components/sections/settings-panel-section"
import { FileUploadSection } from "@/components/sections/file-upload-section"

// Define section types for the bento grid
type SectionSize = "small" | "medium" | "large" | "featured"

interface StyleGuideSection {
  component: ReactNode
  size: SectionSize
  hidden?: boolean
  id: string
  name: string
  isPro?: boolean
}

export function StyleGuide({ packageType = "pro" }: { packageType?: "free" | "pro" }) {
  const { viewMode } = useView()
  const { sidebarVisible } = useSidebar()
  const initialRenderRef = useRef(true)
  const mainContentRef = useRef<HTMLElement | null>(null)
  const hasScrolledToTopRef = useRef(false)
  const { currentTheme } = useMaterial()
  const debugMode = useRef(false)

  // Check for debug mode
  useEffect(() => {
    if (typeof window !== "undefined") {
      debugMode.current = window.location.search.includes("debug=true")
    }
  }, [])

  // Define all sections with their sizes for the bento grid
  const sections: StyleGuideSection[] = [
    // Foundation sections first (in their original order)
    { component: <ColorSection />, size: "medium", id: "color", name: "Color" },
    { component: <IconographySection />, size: "medium", id: "iconography", name: "Iconography" },
    { component: <TypographySection />, size: "medium", id: "typography", name: "Typography" },
    { component: <SpacingSection />, size: "medium", id: "spacing", name: "Spacing" },
    { component: <ElevationSection />, size: "medium", id: "elevation", name: "Elevation" },

    // Component sections in alphabetical order (matching sidebar)
    { component: <AccordionSection />, size: "medium", id: "accordion", name: "Accordion" },
    { component: <AlertsSection />, size: "small", id: "alerts", name: "Alert" },
    { component: <AlertDialogSection />, size: "medium", id: "alert-dialog", name: "Alert Dialog" },
    { component: <AvatarsSection />, size: "small", id: "avatars", name: "Avatar" },
    { component: <BadgesSection />, size: "small", id: "badges", name: "Badge" },
    { component: <BreadcrumbsSection />, size: "small", id: "breadcrumbs", name: "Breadcrumb" },
    { component: <ButtonsSection />, size: "medium", id: "buttons", name: "Button" },
    { component: <CalendarSection />, size: "medium", id: "calendar", name: "Calendar" },
    { component: <CardsSection />, size: "medium", id: "cards", name: "Card" },
    { component: <CheckboxSection />, size: "small", id: "checkbox", name: "Checkbox" },
    { component: <CollapsibleSection />, size: "medium", id: "collapsible", name: "Collapsible" },
    { component: <ComboboxSection />, size: "medium", id: "combobox", name: "Combobox" },
    { component: <ContextMenuSection />, size: "medium", id: "context-menu", name: "Context Menu" },
    { component: <DropdownsSection />, size: "medium", id: "dropdowns", name: "Dropdown" },
    { component: <FormsSection />, size: "large", id: "forms", name: "Form" },
    { component: <HoverCardSection />, size: "medium", id: "hover-card", name: "Hover Card" },
    { component: <LabelSection />, size: "small", id: "label", name: "Label" },
    { component: <ModalsSection />, size: "medium", id: "modals", name: "Modal" },
    { component: <PaginationSection />, size: "small", id: "pagination", name: "Pagination" },
    { component: <ProgressSection />, size: "small", id: "progress", name: "Progress" },
    { component: <ScrollAreaSection />, size: "medium", id: "scroll-area", name: "Scroll Area" },
    { component: <SheetSection />, size: "medium", id: "sheet", name: "Sheet" },
    { component: <SkeletonSection />, size: "medium", id: "skeleton", name: "Skeleton" },
    { component: <SliderSection />, size: "small", id: "slider", name: "Slider" },
    { component: <TabsSection />, size: "medium", id: "tabs", name: "Tab" },
    { component: <TablesSection />, size: "large", id: "tables", name: "Table" },
    { component: <ToggleSection />, size: "small", id: "toggle", name: "Toggle" },
    { component: <TooltipsSection />, size: "small", id: "tooltips", name: "Tooltip" },

    // Pro-only sections
    { component: <ContactFormSection />, size: "medium", id: "contact-form", name: "Contact Form", isPro: true },

    // New app UI blocks
    {
      component: <DashboardStatsSection />,
      size: "large",
      id: "dashboard-stats",
      name: "Dashboard Stats",
      isPro: true,
    },
    { component: <DataTableSection />, size: "large", id: "data-table", name: "Data Table", isPro: true },
    { component: <UserProfileSection />, size: "medium", id: "user-profile", name: "User Profile", isPro: true },
    { component: <SettingsPanelSection />, size: "large", id: "settings-panel", name: "Settings Panel", isPro: true },
    { component: <FileUploadSection />, size: "medium", id: "file-upload", name: "File Upload", isPro: true },

    // Hidden sections
    {
      component: <AdvancedTypographySection />,
      size: "medium",
      id: "advanced-typography",
      name: "Advanced Typography",
      hidden: true,
    },
  ]

  // Filter out hidden sections and respect package type
  const visibleSections = sections.filter((section) => !section.hidden && (packageType === "pro" || !section.isPro))

  // Use useLayoutEffect to handle scroll position before browser paint
  useLayoutEffect(() => {
    // Disable browser scroll restoration
    if (typeof history.scrollRestoration !== "undefined") {
      history.scrollRestoration = "manual"
    }

    // Clear any hash in the URL without triggering navigation
    if (window.location.hash) {
      history.pushState("", document.title, window.location.pathname + window.location.search)
    }

    // Force scroll to top on every render
    const forceScrollTop = () => {
      window.scrollTo(0, 0)
      document.documentElement.scrollTop = 0
      document.body.scrollTop = 0

      // Also reset main content scroll
      const mainContent = document.querySelector(".main-content")
      if (mainContent) {
        mainContent.scrollTop = 0
      }
    }

    // Execute immediately
    forceScrollTop()

    // Mark initial render as complete
    initialRenderRef.current = false
  }, [])

  // Force scroll to top on every render - PRIORITY EFFECT
  useEffect(() => {
    const forceScrollTop = () => {
      // Reset all possible scroll containers
      window.scrollTo(0, 0)
      document.documentElement.scrollTop = 0
      document.body.scrollTop = 0

      // Reset main content specifically
      const mainContent = document.querySelector(".main-content")
      if (mainContent) {
        mainContent.scrollTop = 0
        mainContentRef.current = mainContent as HTMLElement
      }

      // Reset any other scrollable containers
      const scrollableElements = document.querySelectorAll(".overflow-auto, .overflow-y-auto")
      scrollableElements.forEach((el) => {
        if (el.scrollTop !== undefined) el.scrollTop = 0
      })
    }

    // Execute immediately
    forceScrollTop()

    // Execute multiple times to ensure it takes effect
    const timeouts = [
      setTimeout(forceScrollTop, 0),
      setTimeout(forceScrollTop, 1),
      setTimeout(forceScrollTop, 10),
      setTimeout(forceScrollTop, 50),
      setTimeout(forceScrollTop, 100),
      setTimeout(forceScrollTop, 200),
    ]

    return () => {
      timeouts.forEach(clearTimeout)
    }
  }, []) // Empty dependency array - runs on every mount

  // Handle hash-based navigation
  useEffect(() => {
    // Skip hash navigation entirely on initial render
    if (initialRenderRef.current) return

    const handleHashChange = () => {
      const hash = window.location.hash.substring(1)
      if (!hash) return

      if (debugMode.current) {
        console.log(`Hash changed to: ${hash}`)
      }

      // Use requestAnimationFrame to ensure DOM is ready
      requestAnimationFrame(() => {
        const element = document.getElementById(hash)
        const mainContent = mainContentRef.current || document.querySelector(".main-content")

        if (element && mainContent) {
          if (debugMode.current) {
            console.log(`Found element for hash ${hash}:`, element)
            console.log(`Main content:`, mainContent)
          }

          // Try multiple approaches to ensure scrolling works
          try {
            // First approach: direct scrollIntoView
            element.scrollIntoView({ behavior: "smooth", block: "start" })

            // Second approach: calculate position
            setTimeout(() => {
              const elementPosition = element.offsetTop
              mainContent.scrollTop = elementPosition

              if (debugMode.current) {
                console.log(`Scrolled to position: ${elementPosition}`)
              }
            }, 100)
          } catch (error) {
            console.error("Error scrolling to element:", error)
          }
        } else {
          console.error(`Element with id "${hash}" not found or main content not available`)
        }
      })
    }

    // Set up event listener for hash changes
    window.addEventListener("hashchange", handleHashChange)

    // Handle hash in URL on mount, but not on initial render
    if (window.location.hash) {
      handleHashChange()
    }

    return () => window.removeEventListener("hashchange", handleHashChange)
  }, [])

  // Force scroll to top after render
  useEffect(() => {
    if (hasScrolledToTopRef.current) return

    const forceScrollTop = () => {
      const mainContent = document.querySelector(".main-content")
      if (mainContent) {
        mainContentRef.current = mainContent as HTMLElement
        mainContent.scrollTop = 0

        // Mark that we've scrolled to top
        if (mainContent.scrollTop === 0) {
          hasScrolledToTopRef.current = true
        }
      }
    }

    // Execute immediately
    forceScrollTop()

    // And again after delays to ensure it takes effect
    const timeouts = [
      setTimeout(forceScrollTop, 0),
      setTimeout(forceScrollTop, 50),
      setTimeout(forceScrollTop, 100),
      setTimeout(forceScrollTop, 200),
      setTimeout(forceScrollTop, 500),
      setTimeout(forceScrollTop, 1000),
    ]

    return () => {
      timeouts.forEach(clearTimeout)
    }
  }, [])

  // Effect to apply background-primary to all style guide sections
  useEffect(() => {
    const applyBackgroundColor = () => {
      document.querySelectorAll(".style-guide-section").forEach((section) => {
        ;(section as HTMLElement).style.setProperty("background-color", "var(--background-primary)", "important")
      })
    }

    // Apply immediately and after a short delay to ensure it takes effect
    applyBackgroundColor()
    const timeoutId = setTimeout(applyBackgroundColor, 100)

    return () => clearTimeout(timeoutId)
  }, [currentTheme]) // Re-apply when theme changes

  // Add event listener for section navigation
  useEffect(() => {
    const handleSectionNavigation = (event: CustomEvent) => {
      const sectionId = event.detail?.sectionId
      if (!sectionId) return

      if (debugMode.current) {
        console.log(`Navigation event received for section: ${sectionId}`)
      }

      const element = document.getElementById(sectionId)
      if (element && mainContentRef.current) {
        element.scrollIntoView({ behavior: "smooth", block: "start" })
      }
    }

    window.addEventListener("navigate-to-section" as any, handleSectionNavigation as EventListener)

    return () => {
      window.removeEventListener("navigate-to-section" as any, handleSectionNavigation as EventListener)
    }
  }, [])

  // Responsive padding classes - updated for large screens
  const sectionPaddingClasses = cn(
    "pt-32 pb-32", // Top and bottom padding (8rem each)
    "px-4", // Mobile: 1rem padding on left and right
    "md:pl-16 md:pr-80", // Medium+: left 4rem, right 20rem
    "2xl:pl-32", // Extra large screens (1536px+): left 8rem (128px)
    "2xl:pr-96", // Extra large screens (1536px+): right 24rem (384px)
  )

  // Custom background style with !important to override any other styles
  const sectionBackgroundStyle = {
    backgroundColor: "var(--background-primary) !important",
  } as React.CSSProperties

  if (viewMode === "list") {
    // List view - traditional vertical layout
    return (
      <main
        className="overflow-y-auto w-full bg-background-primary main-content"
        ref={(el) => {
          mainContentRef.current = el
        }}
      >
        {/* Add separator between banner and first section */}
        <div className="border-b border-border w-full" />

        {visibleSections.map((section, index) => (
          <React.Fragment key={section.id}>
            <section
              id={section.id}
              style={sectionBackgroundStyle}
              data-use-background-primary="true"
              data-section-id={section.id}
              className={cn(
                "scroll-mt-16 style-guide-section w-full transition-all duration-300 ease-in-out bg-background-primary",
                sectionPaddingClasses,
                section.id === "typography" ? "typography-table-layout" : "",
              )}
            >
              <div className="mx-auto w-full">{section.component}</div>
            </section>
            {index < visibleSections.length - 1 && <Separator className="w-full" />}
          </React.Fragment>
        ))}
        <CascadedComponentDemo />
      </main>
    )
  } else {
    // Grid view - bento grid layout
    return (
      <div className="p-8 max-w-7xl mx-auto">
        <h1 className="text-4xl font-bold mb-2">Design System</h1>
        <p className="text-lg text-muted-foreground mb-8">
          {packageType === "pro"
            ? "Pro Edition with all components and blocks"
            : "Free Edition with essential components"}
        </p>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {/* Foundation Section */}
          <div className="col-span-full bg-card p-6 rounded-lg border">
            <h2 className="text-2xl font-semibold mb-4">Foundation</h2>
            <p className="text-muted-foreground mb-4">
              Core design elements that form the basis of your design system.
            </p>
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
              {["Colors", "Typography", "Spacing", "Iconography", "Elevation"].map((item) => (
                <div key={item} className="bg-muted/50 p-4 rounded-md text-center">
                  {item}
                </div>
              ))}
            </div>
          </div>

          {/* Components Section */}
          <div className="col-span-full bg-card p-6 rounded-lg border">
            <h2 className="text-2xl font-semibold mb-4">Components</h2>
            <p className="text-muted-foreground mb-4">UI components for building interfaces.</p>
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
              {[
                "Button",
                "Card",
                "Input",
                "Checkbox",
                "Radio",
                "Select",
                "Tabs",
                "Dialog",
                "Tooltip",
                "Avatar",
                "Badge",
                "Alert",
                "Toast",
                "Toggle",
                "Dropdown",
                "Progress",
                "Slider",
                "Switch",
                "Table",
                "Pagination",
              ].map((item) => (
                <div key={item} className="bg-muted/50 p-4 rounded-md text-center">
                  {item}
                </div>
              ))}
            </div>
          </div>

          {/* Pro-only Blocks Section */}
          {packageType === "pro" && (
            <div className="col-span-full bg-card p-6 rounded-lg border">
              <div className="flex items-center gap-2 mb-4">
                <h2 className="text-2xl font-semibold">Blocks</h2>
                <span className="bg-primary text-primary-foreground text-xs px-2 py-1 rounded">Pro</span>
              </div>
              <p className="text-muted-foreground mb-4">Pre-built UI blocks for common patterns.</p>
              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
                {[
                  "Hero Section",
                  "Feature Cards",
                  "Pricing Table",
                  "Testimonials",
                  "Contact Form",
                  "Newsletter",
                  "Footer",
                  "Navigation",
                  "Stats",
                ].map((item) => (
                  <div key={item} className="bg-muted/50 p-4 rounded-md text-center">
                    {item}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        <div className="mt-12 text-center text-sm text-muted-foreground">
          <p>Design System {packageType === "pro" ? "Pro" : "Free"} Edition • v1.0.0</p>
        </div>
      </div>
    )
  }
}
