"use client"

import { Moon, Sun } from "lucide-react"
import { useEffect, useState } from "react"
import { Switch } from "@/components/ui/switch"

export function ThemeToggleFab() {
  const [isDark, setIsDark] = useState(false)
  const [mounted, setMounted] = useState(false)

  useEffect(() => {
    setMounted(true)
    // Check if theme is stored in localStorage
    const storedTheme = localStorage.getItem("theme")
    const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches

    if (storedTheme === "dark" || (!storedTheme && prefersDark)) {
      setIsDark(true)
      document.documentElement.classList.add("dark")
    } else {
      setIsDark(false)
      document.documentElement.classList.remove("dark")
    }
  }, [])

  const toggleTheme = () => {
    const newTheme = !isDark
    setIsDark(newTheme)

    if (newTheme) {
      document.documentElement.classList.add("dark")
      localStorage.setItem("theme", "dark")
    } else {
      document.documentElement.classList.remove("dark")
      localStorage.setItem("theme", "light")
    }
  }

  if (!mounted) {
    return null
  }

  return (
    <div className="fixed bottom-8 left-8 z-50 flex items-center gap-3 rounded-full bg-card shadow-lg border border-border p-3 transition-all hover:shadow-xl">
      <Sun className="h-5 w-5 text-muted-foreground" />
      <Switch
        checked={isDark}
        onCheckedChange={toggleTheme}
        className="data-[state=checked]:bg-primary"
        aria-label="Alternar tema"
      />
      <Moon className="h-5 w-5 text-muted-foreground" />
    </div>
  )
}
