"use client"

import { Button } from "@/components/ui/button"
import { Download } from "lucide-react"
import { useDesign } from "@/contexts/design-context"
import { useColorPalette } from "@/contexts/color-context"
import { useMaterial } from "@/contexts/material-context"
import { useState } from "react"
import { exportStyleguide } from "@/utils/export-styleguide"
import { useToast } from "@/components/ui/use-toast"
import { hexToHsl } from "@/utils/color-utils"

export function DownloadFigmaButton() {
  const { borderRadius, font, fontFamily } = useDesign()
  const { primaryColor } = useColorPalette()
  const { selectedMaterial } = useMaterial()
  const [isExporting, setIsExporting] = useState(false)
  const { toast } = useToast()

  const handleExport = async () => {
    setIsExporting(true)
    try {
      // Convert hex primaryColor to HSL
      const hslColor = hexToHsl(primaryColor)

      // Prepare the settings objects in the format expected by exportStyleguide
      const designSettings = {
        borderRadius,
        font,
        fontFamily,
      }

      const colorSettings = {
        primaryColor: hslColor,
        colors: {
          black: "#000000",
          white: "#ffffff",
          gray: "#d9d9d9",
          dark: "#161616",
        },
      }

      const materialSettings = {
        materialType: selectedMaterial?.name || "Flat",
        opacity: selectedMaterial?.name === "Glass" ? selectedMaterial.backgroundPrimary.darkOpacity || 0.85 : 1,
        color: selectedMaterial?.backgroundPrimary?.dark || "#000000",
      }

      const result = await exportStyleguide(designSettings, colorSettings, materialSettings)

      if (result) {
        toast({
          title: "Export Successful",
          description: "Your design system has been exported successfully.",
        })
      } else {
        toast({
          title: "Export Failed",
          description: "There was an error exporting your design system.",
          variant: "destructive",
        })
      }
    } catch (error) {
      console.error("Error exporting design system:", error)
      toast({
        title: "Export Failed",
        description: "There was an error exporting your design system.",
        variant: "destructive",
      })
    } finally {
      setIsExporting(false)
    }
  }

  return (
    <div className="fixed bottom-8 right-8 z-50">
      <Button
        onClick={handleExport}
        disabled={isExporting}
        className="shadow-sm transition-all duration-200 bg-foreground text-background hover:bg-foreground/90 hover:shadow-md"
      >
        <Download className="mr-2 h-4 w-4" />
        {isExporting ? "Exporting..." : "Export Design System"}
      </Button>
    </div>
  )
}
