'use client'

import { cn } from '../../utils'
import { useSidebarContext } from '../Navigation'
import { DarkMode, LightMode, SystemMode } from './icons'

type Mode = 'system' | 'light' | 'dark'

export type DarkModeToggleProps = {
  /** Current theme mode. When undefined, the toggle does not render. */
  theme: string | undefined
  /** Updates the active theme mode. Usually provided by `next-themes`. */
  setTheme: (theme: Mode) => void
}

const Modes: { mode: Mode; icon: React.ReactElement }[] = [
  { mode: 'system', icon: <SystemMode /> },
  { mode: 'light', icon: <LightMode /> },
  { mode: 'dark', icon: <DarkMode /> },
]

export type ThemeToggleProps = {
  /** Theme state and setter used to switch between system, light, and dark modes. */
  darkModeToggle: DarkModeToggleProps
}

/**
 * Compact control for switching between system, light, and dark theme modes.
 * Intended for use inside navigation surfaces such as the Shell sidebar.
 */
export const ThemeToggle = ({ darkModeToggle }: ThemeToggleProps) => {
  const { theme, setTheme } = darkModeToggle

  const sidebarContext = useSidebarContext()

  if (!theme) {
    return null
  }

  return (
    <div
      className={cn(
        'mr-auto mt-auto inline-flex h-8 rounded-full bg-muted-more p-1 md:hidden md:duration-200 md:animate-in md:fade-in md:group-hover:flex',
      )}
    >
      {Modes.map(({ mode, icon }) => (
        <button
          key={mode}
          onClick={() => {
            setTheme(mode)
            if (sidebarContext) {
              const { setOpenMobile } = sidebarContext
              setOpenMobile(false)
            }
          }}
          className={cn(
            'flex h-6 w-6 items-center justify-center rounded-full transition-all',
            theme === mode ? 'bg-background' : 'bg-transparent',
          )}
        >
          {icon}
        </button>
      ))}
    </div>
  )
}
