1"use client";
2
3import { useControllableState } from "@radix-ui/react-use-controllable-state";
4import { Monitor, Moon, Sun } from "lucide-react";
5import { motion } from "motion/react";
6import { useCallback, useEffect, useState } from "react";
7import { cn } from "@/lib/utils";
8
9const themes = [
10 {
11 key: "system",
12 icon: Monitor,
13 label: "System theme",
14 },
15 {
16 key: "light",
17 icon: Sun,
18 label: "Light theme",
19 },
20 {
21 key: "dark",
22 icon: Moon,
23 label: "Dark theme",
24 },
25];
26
27export type ThemeSwitcherProps = {
28 value?: "light" | "dark" | "system";
29 onChange?: (theme: "light" | "dark" | "system") => void;
30 defaultValue?: "light" | "dark" | "system";
31 className?: string;
32};
33
34export const ThemeSwitcher = ({
35 value,
36 onChange,
37 defaultValue = "system",
38 className,
39}: ThemeSwitcherProps) => {
40 const [theme, setTheme] = useControllableState({
41 defaultProp: defaultValue,
42 prop: value,
43 onChange,
44 });
45 const [mounted, setMounted] = useState(false);
46
47 const handleThemeClick = useCallback(
48 (themeKey: "light" | "dark" | "system") => {
49 setTheme(themeKey);
50 },
51 [setTheme]
52 );
53
54 // Prevent hydration mismatch
55 useEffect(() => {
56 setMounted(true);
57 }, []);
58
59 if (!mounted) {
60 return null;
61 }
62
63 return (
64 <div
65 className={cn(
66 "relative isolate flex h-8 rounded-full bg-background p-1 ring-1 ring-border",
67 className
68 )}
69 >
70 {themes.map(({ key, icon: Icon, label }) => {
71 const isActive = theme === key;
72
73 return (
74 <button
75 aria-label={label}
76 className="relative h-6 w-6 rounded-full"
77 key={key}
78 onClick={() => handleThemeClick(key as "light" | "dark" | "system")}
79 type="button"
80 >
81 {isActive && (
82 <motion.div
83 className="absolute inset-0 rounded-full bg-secondary"
84 layoutId="activeTheme"
85 transition={{ type: "spring", duration: 0.5 }}
86 />
87 )}
88 <Icon
89 className={cn(
90 "relative z-10 m-auto h-4 w-4",
91 isActive ? "text-foreground" : "text-muted-foreground"
92 )}
93 />
94 </button>
95 );
96 })}
97 </div>
98 );
99};
100