"use client";

import type { ThemeMode } from "@domainops/shared-types";
import { Segmented, Tooltip } from "antd";
import { BulbOutlined, DesktopOutlined, MoonOutlined } from "@ant-design/icons";
import { useEffect, useState } from "react";
import { updateThemeMode } from "@/lib/api/profile";
import { useAuth } from "@/lib/auth/AuthProvider";
import { useThemeMode, useThemeSettings } from "@/lib/theme/ThemeProvider";

const OPTIONS = [
  { value: "light", label: <BulbOutlined title="Light" /> },
  { value: "dark", label: <MoonOutlined title="Dark" /> },
  { value: "system", label: <DesktopOutlined title="System" /> },
];

/**
 * Light / Dark / System switch in the top bar. Only rendered at all when the
 * site admin has allowed per-user overrides (Settings > Appearance) -
 * otherwise everyone just gets the site default, per theme.mode.
 */
export function ThemeModeSelector({ block = false }: { block?: boolean }) {
  const { user } = useAuth();
  const theme = useThemeSettings();
  const { mode, setMode } = useThemeMode();
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    // Sync the user's saved preference into ThemeProvider once, on load -
    // a one-time hydration from the server's source of truth, not a
    // state-sync bug.
    if (user?.theme_mode) setMode(user.theme_mode);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.id]);

  if (!theme.allow_user_override) return null;

  async function handleChange(value: ThemeMode) {
    setMode(value);
    setIsSaving(true);
    try {
      await updateThemeMode(value);
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <div className="shrink-0 dms__theme-mode">
      <Tooltip title="Your personal light / dark / system preference">
        <Segmented
          block={block}
          size="small"
          value={mode ?? theme.mode}
          disabled={isSaving}
          onChange={(value) => void handleChange(value as ThemeMode)}
          options={OPTIONS}
        />
      </Tooltip>
    </div>
  );
}
