"use client"

import { useState, useEffect } from "react"
import { Download } from "lucide-react"
import { useTheme } from "next-themes"
import { ExportPackagesOverlay } from "./export-packages-overlay"
import { Button } from "@/components/ui/button"

export function ExportButtons() {
  const { theme, resolvedTheme } = useTheme()
  const [mounted, setMounted] = useState(false)
  const [isOverlayOpen, setIsOverlayOpen] = useState(false)
  const [currentTheme, setCurrentTheme] = useState<string | undefined>(undefined)

  // Effect to handle mounting and theme detection
  useEffect(() => {
    setMounted(true)

    // Get the initial theme directly from localStorage or document class
    const initialTheme =
      typeof localStorage !== "undefined"
        ? localStorage.getItem("theme")
        : typeof document !== "undefined"
          ? document.documentElement.classList.contains("dark")
            ? "dark"
            : "light"
          : "light"

    setCurrentTheme(initialTheme || "light")

    // Update currentTheme whenever resolvedTheme changes
    if (resolvedTheme) {
      setCurrentTheme(resolvedTheme)
    }
  }, [resolvedTheme])

  const handleOpenOverlay = () => {
    setIsOverlayOpen(true)
    if (typeof document !== "undefined") {
      document.body.style.overflow = "hidden"
    }
  }

  const handleCloseOverlay = () => {
    setIsOverlayOpen(false)
    if (typeof document !== "undefined") {
      document.body.style.overflow = ""
    }
  }

  // Only render the button when mounted to prevent hydration mismatch
  if (!mounted) {
    return <div className="flex flex-col gap-2 mt-auto h-10 opacity-0">Loading...</div>
  }

  return (
    <>
      <div className="flex flex-col gap-2 mt-auto w-full">
        <Button
          size="sm"
          variant="default"
          onClick={handleOpenOverlay}
          className="w-full shadow-sm flex items-center justify-center h-8 text-sm"
        >
          <Download className="mr-1.5 h-4 w-4" />
          Export Design System
        </Button>
      </div>

      {mounted && <ExportPackagesOverlay open={isOverlayOpen} onOpenChange={handleCloseOverlay} />}
    </>
  )
}
