"use client"

import { useTheme } from "next-themes"
import { useEffect, useState } from "react"

import { Button } from "@/components/ui/button"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"

// Remove this import:
// import { Moon, Sun } from 'lucide-react'

// Add this import:
import { Sun, Moon } from "lucide-react"

export function ThemeToggle() {
  const { setTheme, theme, resolvedTheme } = useTheme()
  const [mounted, setMounted] = useState(false)

  // Only render the toggle after mounting to avoid hydration mismatch
  useEffect(() => {
    setMounted(true)
  }, [])

  // Force theme update when theme changes
  useEffect(() => {
    if (!mounted) return

    // Force theme update
    const actualTheme = theme === "system" ? resolvedTheme || "light" : theme || "light"

    // Remove both theme classes first
    document.documentElement.classList.remove("light", "dark")

    // Add the correct theme class
    document.documentElement.classList.add(actualTheme)
    document.documentElement.style.colorScheme = actualTheme

    console.log("Theme toggled to:", theme, "Resolved theme:", actualTheme)
  }, [theme, resolvedTheme, mounted])

  if (!mounted) {
    return (
      <Button variant="ghost" size="icon" className="h-8 w-8 rounded-md">
        <span className="sr-only">Toggle theme</span>
      </Button>
    )
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant="ghost"
          size="icon"
          onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
          className="h-7 w-7 px-0"
          style={{ borderRadius: "6px" }}
        >
          <Sun className="h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
          <Moon className="absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
          <span className="sr-only">Toggle theme</span>
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="p-1">
        <DropdownMenuItem
          onClick={() => {
            setTheme("light")
            console.log("Setting theme to light")
          }}
          className="flex items-center text-xs px-2 py-1.5 cursor-pointer"
        >
          <Sun className="h-3.5 w-3.5 mr-2" />
          Light
          {theme === "light" && <span className="ml-auto">✓</span>}
        </DropdownMenuItem>
        <DropdownMenuItem
          onClick={() => {
            setTheme("dark")
            console.log("Setting theme to dark")
          }}
          className="flex items-center text-xs px-2 py-1.5 cursor-pointer"
        >
          <Moon className="h-3.5 w-3.5 mr-2" />
          Dark
          {theme === "dark" && <span className="ml-auto">✓</span>}
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
