"use client"

import type React from "react"

import { useState, useRef, useEffect } from "react"
import { createPortal } from "react-dom"
import { Button } from "@/components/ui/button"
import { SectionHeading } from "@/components/ui/section-heading"
import { ComponentContainer } from "@/components/ui/component-container"
import {
  User,
  Settings,
  CreditCard,
  UserPlus,
  Cloud,
  LogOut,
  ChevronRight,
  Check,
  Laptop,
  Moon,
  Sun,
} from "lucide-react"

// Update the DropdownsSection component to include a properties toggle
export function DropdownsSection() {
  return (
    <div className="space-y-8">
      <SectionHeading
        title="Dropdown Menus"
        description="Interactive dropdown menus with proper positioning and viewport constraints."
      />

      <ComponentContainer
        title="Dropdown Menu"
        properties={[
          {
            name: "alignment",
            type: "select",
            options: ["left", "right"],
            defaultValue: "left",
            label: "Alignment",
            description: "Controls the horizontal alignment of the dropdown menu relative to its trigger.",
          },
        ]}
        renderComponent={(props) => (
          <div className="flex items-center justify-center min-h-[200px] p-6">
            <EnhancedDropdown alignment={props.alignment} />
          </div>
        )}
        generateCode={(props) => `<DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button>Open Menu</Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="${props.alignment}">
            <DropdownMenuLabel>My Account</DropdownMenuLabel>
            <DropdownMenuSeparator />
            <DropdownMenuItem>
              <User className="mr-2 h-4 w-4" />
              <span>Profile</span>
              <DropdownMenuShortcut>⇧⌘P</DropdownMenuShortcut>
            </DropdownMenuItem>
            <DropdownMenuItem>
              <CreditCard className="mr-2 h-4 w-4" />
              <span>Billing</span>
              <DropdownMenuShortcut>⌘B</DropdownMenuShortcut>
            </DropdownMenuItem>
            <DropdownMenuSub>
              <DropdownMenuSubTrigger>
                <Settings className="mr-2 h-4 w-4" />
                <span>Settings</span>
              </DropdownMenuSubTrigger>
              <DropdownMenuSubContent>
                <DropdownMenuItem>
                  <User className="mr-2 h-4 w-4" />
                  <span>Account</span>
                </DropdownMenuItem>
                <DropdownMenuItem>
                  <Bell className="mr-2 h-4 w-4" />
                  <span>Notifications</span>
                </DropdownMenuItem>
                <DropdownMenuItem>
                  <Laptop className="mr-2 h-4 w-4" />
                  <span>Appearance</span>
                </DropdownMenuItem>
              </DropdownMenuSubContent>
            </DropdownMenuSub>
            <DropdownMenuSeparator />
            <DropdownMenuCheckboxItem checked>
              Show notifications
            </DropdownMenuCheckboxItem>
            <DropdownMenuSeparator />
            <DropdownMenuRadioGroup value="system">
              <DropdownMenuLabel>Theme</DropdownMenuLabel>
              <DropdownMenuRadioItem value="light">
                <Sun className="mr-2 h-4 w-4" />
                Light
              </DropdownMenuRadioItem>
              <DropdownMenuRadioItem value="dark">
                <Moon className="mr-2 h-4 w-4" />
                Dark
              </DropdownMenuRadioItem>
              <DropdownMenuRadioItem value="system">
                <Laptop className="mr-2 h-4 w-4" />
                System
              </DropdownMenuRadioItem>
            </DropdownMenuRadioGroup>
          </DropdownMenuContent>
        </DropdownMenu>`}
      />
    </div>
  )
}

type DropdownAlignment = "left" | "right"

interface EnhancedDropdownProps {
  alignment?: DropdownAlignment
}

function EnhancedDropdown({ alignment = "left" }: EnhancedDropdownProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [showNotifications, setShowNotifications] = useState(true)
  const [theme, setTheme] = useState("system")
  const [position, setPosition] = useState({ top: 0, left: 0, transformOrigin: "top left" })
  const [mounted, setMounted] = useState(false)
  const [activeSubmenu, setActiveSubmenu] = useState<string | null>(null)
  const [submenuPosition, setSubmenuPosition] = useState({ top: 0, left: 0 })
  const buttonRef = useRef<HTMLButtonElement>(null)
  const dropdownRef = useRef<HTMLDivElement>(null)
  const submenuTriggerRef = useRef<HTMLDivElement>(null)

  // Mount effect
  useEffect(() => {
    setMounted(true)
    return () => setMounted(false)
  }, [])

  // Update position when dropdown opens or alignment changes
  useEffect(() => {
    if (isOpen && buttonRef.current) {
      const updatePosition = () => {
        if (!buttonRef.current) return

        const rect = buttonRef.current.getBoundingClientRect()
        const viewportWidth = window.innerWidth
        const viewportHeight = window.innerHeight
        const dropdownWidth = 224 // 14rem = 224px
        const gap = 16 // 1rem gap from edges

        // Estimate dropdown height (will be refined once it renders)
        const estimatedHeight = dropdownRef.current?.offsetHeight || 400

        // Calculate horizontal position based on alignment
        let left: number
        if (alignment === "left") {
          left = rect.left
          // Ensure dropdown doesn't overflow right edge
          if (left + dropdownWidth > viewportWidth - gap) {
            left = Math.max(gap, viewportWidth - dropdownWidth - gap)
          }
        } else {
          // Right alignment
          left = rect.right - dropdownWidth
          // Ensure dropdown doesn't overflow left edge
          if (left < gap) {
            left = gap
          }
        }

        // Calculate available space below and above
        const spaceBelow = viewportHeight - rect.bottom - gap
        const spaceAbove = rect.top - gap

        let top: number
        let transformOrigin: string

        // Default: position below button if there's enough space
        if (spaceBelow >= estimatedHeight || spaceBelow >= spaceAbove) {
          top = rect.bottom + 8 // 8px gap between button and dropdown
          transformOrigin = alignment === "left" ? "top left" : "top right"

          // Ensure dropdown doesn't overflow bottom edge
          if (top + estimatedHeight > viewportHeight - gap) {
            // Adjust height to fit available space with gap
            const maxHeight = viewportHeight - top - gap
            if (dropdownRef.current) {
              dropdownRef.current.style.maxHeight = `${maxHeight}px`
              dropdownRef.current.style.overflowY = "auto"
            }
          }
        } else {
          // Position above button if more space above than below
          top = rect.top - 8 - estimatedHeight // 8px gap between button and dropdown
          transformOrigin = alignment === "left" ? "bottom left" : "bottom right"

          // Ensure dropdown doesn't overflow top edge
          if (top < gap) {
            top = gap
            const maxHeight = rect.top - gap - 8
            if (dropdownRef.current) {
              dropdownRef.current.style.maxHeight = `${maxHeight}px`
              dropdownRef.current.style.overflowY = "auto"
            }
          }
        }

        setPosition({ top, left, transformOrigin })
      }

      // Initial position calculation
      updatePosition()

      // Recalculate position when window is resized
      window.addEventListener("resize", updatePosition)

      // Cleanup
      return () => {
        window.removeEventListener("resize", updatePosition)
      }
    }
  }, [isOpen, alignment])

  // Update submenu position when active
  useEffect(() => {
    if (activeSubmenu && submenuTriggerRef.current) {
      const rect = submenuTriggerRef.current.getBoundingClientRect()
      const viewportWidth = window.innerWidth
      const submenuWidth = 180 // Approximate width

      // Position to the right of the parent menu by default
      // Add a -4px (px-1) overlap by subtracting 4px from the right position
      let left = rect.right - 4

      // If it would go off the right edge, position to the left with overlap
      if (left + submenuWidth > viewportWidth - 16) {
        left = rect.left - submenuWidth + 4
      }

      setSubmenuPosition({
        top: rect.top - 1, // Slight vertical adjustment for better alignment
        left,
      })
    }
  }, [activeSubmenu])

  // Toggle dropdown
  const toggleDropdown = () => {
    setIsOpen(!isOpen)
    setActiveSubmenu(null) // Close any open submenu
  }

  // Close dropdown
  const closeDropdown = () => {
    setIsOpen(false)
    setActiveSubmenu(null)
  }

  // Handle menu item click
  const handleMenuItemClick = (action: string) => {
    console.log(`Action: ${action}`)
    closeDropdown()
  }

  // Toggle checkbox
  const toggleNotifications = () => {
    setShowNotifications(!showNotifications)
  }

  // Set theme
  const handleThemeChange = (newTheme: string) => {
    setTheme(newTheme)
  }

  // Toggle submenu
  const toggleSubmenu = (name: string) => {
    setActiveSubmenu(activeSubmenu === name ? null : name)
  }

  return (
    <div className="relative inline-block text-left">
      {/* Trigger button */}
      <Button ref={buttonRef} onClick={toggleDropdown}>
        Open Menu
      </Button>

      {/* Portal dropdown */}
      {mounted &&
        isOpen &&
        createPortal(
          <>
            {/* Backdrop for closing dropdown when clicking outside */}
            <div className="fixed inset-0 z-[9998]" onClick={closeDropdown} />

            {/* Dropdown content */}
            <div
              ref={dropdownRef}
              className="fixed z-[9999] w-56 rounded-md shadow-md bg-[var(--background-primary)] border border-border animate-in fade-in-0 zoom-in-95 px-1"
              style={{
                top: `${position.top}px`,
                left: `${position.left}px`,
                minWidth: "14rem",
                transformOrigin: position.transformOrigin,
              }}
            >
              <div className="py-1 rounded-md text-popover-foreground">
                {/* Account section */}
                <div className="px-3 py-1.5 text-sm font-semibold">My Account</div>
                <div className="h-px bg-muted my-1" />

                <button
                  className="flex items-center w-full px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground rounded-sm transition-colors"
                  onClick={() => handleMenuItemClick("profile")}
                >
                  <User className="mr-2 h-4 w-4" />
                  <span>Profile</span>
                  <span className="ml-auto text-xs text-muted-foreground">⇧⌘P</span>
                </button>

                <button
                  className="flex items-center w-full px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground rounded-sm transition-colors"
                  onClick={() => handleMenuItemClick("billing")}
                >
                  <CreditCard className="mr-2 h-4 w-4" />
                  <span>Billing</span>
                  <span className="ml-auto text-xs text-muted-foreground">⌘B</span>
                </button>

                {/* Settings submenu trigger */}
                <div
                  ref={submenuTriggerRef}
                  className="flex items-center justify-between w-full px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground rounded-sm cursor-pointer transition-colors"
                  onClick={() => toggleSubmenu("settings")}
                >
                  <div className="flex items-center">
                    <Settings className="mr-2 h-4 w-4" />
                    <span>Settings</span>
                  </div>
                  <ChevronRight className="h-4 w-4" />
                </div>

                <div className="h-px bg-muted my-1" />

                {/* Team section */}
                <button
                  className="flex items-center w-full px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground rounded-sm transition-colors"
                  onClick={() => handleMenuItemClick("invite")}
                >
                  <UserPlus className="mr-2 h-4 w-4" />
                  <span>Invite users</span>
                </button>

                <button
                  className="flex items-center w-full px-3 py-1.5 text-sm text-muted-foreground cursor-not-allowed"
                  disabled
                >
                  <Cloud className="mr-2 h-4 w-4" />
                  <span>API</span>
                </button>

                <div className="h-px bg-muted my-1" />

                {/* Notifications checkbox */}
                <button
                  className="flex items-center w-full px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground rounded-sm transition-colors"
                  onClick={toggleNotifications}
                >
                  <div className="flex items-center flex-1">
                    <span className="absolute left-4 flex h-3.5 w-3.5 items-center justify-center">
                      {showNotifications && <Check className="h-4 w-4" />}
                    </span>
                    <span className="pl-6">Show notifications</span>
                  </div>
                </button>

                <div className="h-px bg-muted my-1" />

                {/* Theme section */}
                <div className="px-3 py-1.5 text-sm font-semibold">Theme</div>

                <button
                  className="flex items-center w-full px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground rounded-sm transition-colors pl-9 relative"
                  onClick={() => handleThemeChange("light")}
                >
                  <span className="absolute left-4 flex h-3.5 w-3.5 items-center justify-center">
                    {theme === "light" && <Circle className="h-2 w-2 fill-current" />}
                  </span>
                  <span className="flex items-center">
                    <Sun className="mr-2 h-4 w-4" />
                    Light
                  </span>
                </button>

                <button
                  className="flex items-center w-full px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground rounded-sm transition-colors pl-9 relative"
                  onClick={() => handleThemeChange("dark")}
                >
                  <span className="absolute left-4 flex h-3.5 w-3.5 items-center justify-center">
                    {theme === "dark" && <Circle className="h-2 w-2 fill-current" />}
                  </span>
                  <span className="flex items-center">
                    <Moon className="mr-2 h-4 w-4" />
                    Dark
                  </span>
                </button>

                <button
                  className="flex items-center w-full px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground rounded-sm transition-colors pl-9 relative"
                  onClick={() => handleThemeChange("system")}
                >
                  <span className="absolute left-4 flex h-3.5 w-3.5 items-center justify-center">
                    {theme === "system" && <Circle className="h-2 w-2 fill-current" />}
                  </span>
                  <span className="flex items-center">
                    <Laptop className="mr-2 h-4 w-4" />
                    System
                  </span>
                </button>

                <div className="h-px bg-muted my-1" />

                {/* Logout */}
                <button
                  className="flex items-center w-full px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground rounded-sm transition-colors"
                  onClick={() => handleMenuItemClick("logout")}
                >
                  <LogOut className="mr-2 h-4 w-4" />
                  <span>Log out</span>
                  <span className="ml-auto text-xs text-muted-foreground">⇧⌘Q</span>
                </button>
              </div>
            </div>

            {/* Submenu */}
            {activeSubmenu === "settings" && (
              <div
                className="fixed z-[10000] w-44 rounded-md shadow-md bg-[var(--background-primary)] border border-border py-1 px-1 animate-in fade-in-0 zoom-in-95"
                style={{
                  top: `${submenuPosition.top}px`,
                  left: `${submenuPosition.left}px`,
                  transformOrigin: "top left",
                }}
              >
                <button
                  className="flex items-center w-full px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground rounded-sm transition-colors"
                  onClick={() => handleMenuItemClick("account-settings")}
                >
                  <User className="mr-2 h-4 w-4" />
                  <span>Account</span>
                </button>
                <button
                  className="flex items-center w-full px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground rounded-sm transition-colors"
                  onClick={() => handleMenuItemClick("notification-settings")}
                >
                  <Bell className="mr-2 h-4 w-4" />
                  <span>Notifications</span>
                </button>
                <button
                  className="flex items-center w-full px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground rounded-sm transition-colors"
                  onClick={() => handleMenuItemClick("appearance-settings")}
                >
                  <Laptop className="mr-2 h-4 w-4" />
                  <span>Appearance</span>
                </button>
              </div>
            )}
          </>,
          document.body,
        )}
    </div>
  )
}

// Import missing icons
function Bell(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg
      {...props}
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9" />
      <path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" />
    </svg>
  )
}

function Circle(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg
      {...props}
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <circle cx="12" cy="12" r="10" />
    </svg>
  )
}
