import { useEffect, useState } from "react";
import { Button } from "./@patternfly/react-core";
import { MoonIcon, SunIcon } from "./@patternfly/react-icons";
import {
    getConsoleColorMode,
    subscribeToConsoleColorMode,
    toggleConsoleColorMode
} from "./consoleColorScheme";

function labels(isDark: boolean) {
    const isChinese = document.documentElement.lang.toLowerCase().startsWith("zh");

    if (isChinese) {
        return {
            current: isDark ? "暗色" : "亮色",
            action: isDark ? "切换至亮色模式" : "切换至暗色模式"
        };
    }

    return {
        current: isDark ? "Dark" : "Light",
        action: isDark ? "Switch to light mode" : "Switch to dark mode"
    };
}

export function ThemeModeToggle() {
    const [mode, setMode] = useState(getConsoleColorMode);

    useEffect(() => subscribeToConsoleColorMode(setMode), []);

    if (document.documentElement.dataset.consoleDarkAllowed === "false") {
        return null;
    }

    const isDark = mode === "dark";
    const copy = labels(isDark);

    return (
        <Button
            variant="plain"
            className="console-theme-toggle"
            aria-label={copy.action}
            title={copy.action}
            aria-pressed={isDark}
            icon={isDark ? <MoonIcon /> : <SunIcon />}
            onClick={toggleConsoleColorMode}
        >
            <span className="console-theme-toggle__label">{copy.current}</span>
        </Button>
    );
}
