"use client"

import { useState, useRef, useEffect } from "react"
import { ChevronLeft, ChevronRight } from "lucide-react"
import { Button } from "@/components/ui/button"
import { useMaterial } from "@/contexts/material-context"
import { cn } from "@/lib/utils"
import { useTheme } from "next-themes"
import { DashboardExample } from "./example-interfaces/dashboard-example"
import { EcommerceExample } from "./example-interfaces/ecommerce-example"
import { SocialFeedExample } from "./example-interfaces/social-feed-example"
import { AdminPanelExample } from "./example-interfaces/admin-panel-example"
import { MediaPlayerExample } from "./example-interfaces/media-player-example"
import { MessagingAppExample } from "./example-interfaces/messaging-app-example"

// Example interfaces to showcase
const examples = [
  {
    name: "Dashboard",
    description: "Analytics dashboard with charts and stats",
    component: DashboardExample,
  },
  {
    name: "E-commerce",
    description: "Product listing with filters and cart",
    component: EcommerceExample,
  },
  {
    name: "Social Feed",
    description: "Social media timeline with posts and comments",
    component: SocialFeedExample,
  },
  {
    name: "Admin Panel",
    description: "User management and settings interface",
    component: AdminPanelExample,
  },
  {
    name: "Media Player",
    description: "Music streaming app with playlist",
    component: MediaPlayerExample,
  },
  {
    name: "Messaging App",
    description: "Chat interface with conversation list",
    component: MessagingAppExample,
  },
]

export function ExampleGallery() {
  const [activeIndex, setActiveIndex] = useState(0)
  const scrollContainerRef = useRef<HTMLDivElement>(null)
  const { selectedMaterial, getBackgroundPrimaryColor } = useMaterial()
  const { theme } = useTheme()

  // Check if the Glass material is selected
  const isGlassMaterial = selectedMaterial?.name === "Glass"

  // Get the background primary color
  const backgroundPrimaryColor = getBackgroundPrimaryColor()

  // Create a style for the cards that uses the background primary color
  const cardStyle = {
    background: isGlassMaterial
      ? `var(--background-primary, ${theme === "dark" ? "rgba(22, 22, 22, 0.7)" : "rgba(255, 255, 255, 0.7)"})`
      : "var(--background-primary)",
    backdropFilter: isGlassMaterial ? "blur(36px)" : "none",
  }

  const scrollToExample = (index: number) => {
    if (scrollContainerRef.current) {
      const container = scrollContainerRef.current
      const items = container.querySelectorAll(".example-item")
      if (items[index]) {
        container.scrollTo({
          left:
            items[index].getBoundingClientRect().left + container.scrollLeft - container.getBoundingClientRect().left,
          behavior: "smooth",
        })
        setActiveIndex(index)
      }
    }
  }

  const handleScroll = () => {
    if (scrollContainerRef.current) {
      const container = scrollContainerRef.current
      const items = container.querySelectorAll(".example-item")
      const containerLeft = container.getBoundingClientRect().left
      const containerCenter = containerLeft + container.offsetWidth / 2

      let closestIndex = 0
      let closestDistance = Number.POSITIVE_INFINITY

      items.forEach((item, index) => {
        const itemRect = item.getBoundingClientRect()
        const itemCenter = itemRect.left + itemRect.width / 2
        const distance = Math.abs(containerCenter - itemCenter)

        if (distance < closestDistance) {
          closestDistance = distance
          closestIndex = index
        }
      })

      if (closestIndex !== activeIndex) {
        setActiveIndex(closestIndex)
      }
    }
  }

  useEffect(() => {
    const container = scrollContainerRef.current
    if (container) {
      container.addEventListener("scroll", handleScroll)
      return () => container.removeEventListener("scroll", handleScroll)
    }
  }, [])

  return (
    <section id="example-interfaces" className="mb-16 pt-8">
      <div className="flex items-center justify-between mb-8">
        <div>
          <h2 className="text-3xl font-semibold tracking-tight text-foreground">Example Interfaces</h2>
          <p className="text-muted-foreground text-sm mt-1">
            See how your customizations look in real-world interfaces
          </p>
        </div>
        <div className="flex gap-2">
          <Button
            variant="outline"
            size="icon"
            onClick={() => scrollToExample(Math.max(0, activeIndex - 1))}
            disabled={activeIndex === 0}
            className="h-8 w-8"
          >
            <ChevronLeft className="h-4 w-4" />
          </Button>
          <Button
            variant="outline"
            size="icon"
            onClick={() => scrollToExample(Math.min(examples.length - 1, activeIndex + 1))}
            disabled={activeIndex === examples.length - 1}
            className="h-8 w-8"
          >
            <ChevronRight className="h-4 w-4" />
          </Button>
        </div>
      </div>

      <div
        ref={scrollContainerRef}
        className="flex overflow-x-auto pb-8 gap-4 hide-scrollbar snap-x snap-mandatory"
        style={{
          scrollbarWidth: "none",
          msOverflowStyle: "none",
          aspectRatio: "16/10",
          minHeight: "500px",
        }}
      >
        {examples.map((example, index) => {
          const ExampleComponent = example.component

          return (
            <div
              key={example.name}
              className={cn(
                "example-item flex-shrink-0 w-[98%] md:w-[98%] lg:w-[98%] rounded-xl overflow-hidden border border-border snap-center flex flex-col",
                activeIndex === index ? "ring-2 ring-primary ring-offset-2 ring-offset-background" : "",
              )}
              style={{
                ...cardStyle,
                aspectRatio: "16/10",
              }}
            >
              <div className="p-4 border-b">
                <h3 className="text-xl font-semibold text-foreground">{example.name}</h3>
                <p className="text-sm text-muted-foreground mt-1">{example.description}</p>
              </div>
              <div className="flex-1 overflow-hidden">
                <ExampleComponent />
              </div>
            </div>
          )
        })}
      </div>

      <div className="flex justify-center gap-2 mt-8">
        {examples.map((_, index) => (
          <button
            key={index}
            className={cn("w-2 h-2 rounded-full transition-all", activeIndex === index ? "bg-primary w-6" : "bg-muted")}
            onClick={() => scrollToExample(index)}
            aria-label={`Go to example ${index + 1}`}
          />
        ))}
      </div>
    </section>
  )
}
