import React from "react";
import { Moon, Sun } from "lucide-react";
import { useTheme } from "next-themes";
import useThemeUpdater from "@/hooks/useThemeUpdater"; 
import useTranslation from "@/hooks/useTranslation"; // <--- Import Hook

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

export default function ThemeToggle() {
  const { setTheme } = useTheme();
  const { updateTheme } = useThemeUpdater(); 
  const { t } = useTranslation(); // <--- Initialize Hook

  const handleThemeChange = (newTheme) => {
    // 1. Instantly update the UI
    setTheme(newTheme);
    // 2. Save the preference to the database in the background
    updateTheme(newTheme);
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="ghost" size="icon">
          <Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
          <Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
          <span className="sr-only">{t('_toggle_theme', 'Toggle theme')}</span>
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end">
        <DropdownMenuItem onClick={() => handleThemeChange("light")}>
          {t('_theme_light', 'Light')}
        </DropdownMenuItem>
        <DropdownMenuItem onClick={() => handleThemeChange("dark")}>
          {t('_theme_dark', 'Dark')}
        </DropdownMenuItem>
        <DropdownMenuItem onClick={() => handleThemeChange("system")}>
          {t('_theme_system', 'System')}
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}