"use client";

import { Moon, Sun } from "lucide-react";
import {
  createContext,
  type ReactNode,
  useContext,
  useMemo,
  useState,
} from "react";

import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

type DashboardTheme = "light" | "dark";

type DashboardThemeContextValue = {
  theme: DashboardTheme;
  toggleTheme: () => void;
};

const storageKey = "webdev-dashboard-theme";

const DashboardThemeContext =
  createContext<DashboardThemeContextValue | null>(null);

export function DashboardThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<DashboardTheme>(() => {
    if (typeof window === "undefined") {
      return "light";
    }

    const storedTheme = window.localStorage.getItem(storageKey);

    if (storedTheme === "dark" || storedTheme === "light") {
      return storedTheme;
    }

    return "light";
  });

  const value = useMemo<DashboardThemeContextValue>(
    () => ({
      theme,
      toggleTheme: () => {
        setTheme((currentTheme) => {
          const nextTheme = currentTheme === "dark" ? "light" : "dark";
          window.localStorage.setItem(storageKey, nextTheme);
          return nextTheme;
        });
      },
    }),
    [theme],
  );

  return (
    <DashboardThemeContext.Provider value={value}>
      <div
        suppressHydrationWarning
        className={cn(
          "min-h-dvh bg-background text-foreground md:flex",
          theme === "dark" && "dark",
        )}
      >
        {children}
      </div>
    </DashboardThemeContext.Provider>
  );
}

export function DashboardThemeToggle() {
  const context = useContext(DashboardThemeContext);

  if (!context) {
    return null;
  }

  const isDark = context.theme === "dark";
  const Icon = isDark ? Sun : Moon;

  return (
    <Button
      className="w-full justify-start"
      variant="ghost"
      onClick={context.toggleTheme}
      aria-pressed={isDark}
    >
      <Icon />
      {isDark ? "Hellmodus" : "Dunkelmodus"}
    </Button>
  );
}
