"use client"

import { useState, useRef, useEffect } from "react"
import { createPortal } from "react-dom"
import { ComponentContainer } from "@/components/ui/component-container"
import { SectionHeading } from "@/components/ui/section-heading"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { CalendarDays } from "lucide-react"

export function HoverCardSection() {
  const [isOpen, setIsOpen] = useState(false)
  const [position, setPosition] = useState({ top: 0, left: 0 })
  const [placement, setPlacement] = useState<"top" | "bottom">("bottom")
  const triggerRef = useRef<HTMLAnchorElement>(null)
  const cardRef = useRef<HTMLDivElement>(null)
  const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(null)

  // Set up portal container
  useEffect(() => {
    setPortalContainer(document.body)
  }, [])

  // Calculate position when open state changes or on window resize
  useEffect(() => {
    if (!isOpen || !triggerRef.current || !cardRef.current) return

    const updatePosition = () => {
      const triggerRect = triggerRef.current!.getBoundingClientRect()
      const cardRect = cardRef.current!.getBoundingClientRect()

      // Check if there's enough space below
      const spaceBelow = window.innerHeight - triggerRect.bottom
      const spaceNeeded = cardRect.height + 8 // 8px offset

      const newPlacement = spaceBelow >= spaceNeeded ? "bottom" : "top"
      setPlacement(newPlacement)

      // Calculate position
      const left = triggerRect.left + triggerRect.width / 2 - cardRect.width / 2
      const top = newPlacement === "bottom" ? triggerRect.bottom + 8 : triggerRect.top - cardRect.height - 8

      setPosition({
        left: Math.max(16, Math.min(left, window.innerWidth - cardRect.width - 16)),
        top,
      })
    }

    // Initial position calculation
    updatePosition()

    // Update position on resize
    window.addEventListener("resize", updatePosition)
    return () => window.removeEventListener("resize", updatePosition)
  }, [isOpen])

  return (
    <section id="hover-card" className="scroll-mt-16">
      <SectionHeading title="Hover Card" description="For sighted users to preview content available behind a link." />

      <div className="space-y-8">
        <ComponentContainer
          title="Basic Hover Card"
          description="A simple hover card with a trigger and content."
          code={`import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { CalendarDays } from 'lucide-react'

<HoverCard>
  <HoverCardTrigger asChild>
    <a
      href="#"
      className="text-sm font-medium underline underline-offset-4"
    >
      @nextjs
    </a>
  </HoverCardTrigger>
  <HoverCardContent className="w-80">
    <div className="flex justify-between space-x-4">
      <Avatar>
        <AvatarImage src="/avatar-man-1.png" />
        <AvatarFallback>VC</AvatarFallback>
      </Avatar>
      <div className="space-y-1">
        <h4 className="text-sm font-semibold">@nextjs</h4>
        <p className="text-sm">
          The React Framework – created and maintained by @vercel.
        </p>
        <div className="flex items-center pt-2">
          <CalendarDays className="mr-2 h-4 w-4 opacity-70" />
          <span className="text-xs text-muted-foreground">
            Joined December 2021
          </span>
        </div>
      </div>
    </div>
  </HoverCardContent>
</HoverCard>`}
        >
          <div className="flex items-center justify-center p-6">
            <a
              ref={triggerRef}
              href="#"
              className="text-sm font-medium underline underline-offset-4"
              onClick={(e) => e.preventDefault()}
              onMouseEnter={() => setIsOpen(true)}
              onMouseLeave={() => setIsOpen(false)}
            >
              @nextjs
            </a>

            {isOpen &&
              portalContainer &&
              createPortal(
                <div
                  ref={cardRef}
                  className="fixed z-50 w-80 rounded-md border bg-popover p-4 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95"
                  style={{
                    top: `${position.top}px`,
                    left: `${position.left}px`,
                    transformOrigin: placement === "top" ? "bottom center" : "top center",
                  }}
                  onMouseEnter={() => setIsOpen(true)}
                  onMouseLeave={() => setIsOpen(false)}
                >
                  <div className="flex justify-between space-x-4">
                    <Avatar>
                      <AvatarImage src="/avatar-man-1.png" />
                      <AvatarFallback>VC</AvatarFallback>
                    </Avatar>
                    <div className="space-y-1">
                      <h4 className="text-sm font-semibold">@nextjs</h4>
                      <p className="text-sm">The React Framework – created and maintained by @vercel.</p>
                      <div className="flex items-center pt-2">
                        <CalendarDays className="mr-2 h-4 w-4 opacity-70" />
                        <span className="text-xs text-muted-foreground">Joined December 2021</span>
                      </div>
                    </div>
                  </div>
                </div>,
                portalContainer,
              )}
          </div>
        </ComponentContainer>
      </div>

      <div className="space-y-4 mt-8">
        <h3 className="text-xl font-medium">Usage</h3>
        <div className="rounded-md border p-4">
          <pre className="text-sm text-muted-foreground overflow-x-auto whitespace-pre-wrap break-words">
            <code>{`import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card"`}</code>
          </pre>
        </div>
      </div>
    </section>
  )
}
