'use client';

import { Moon, Sun } from 'lucide-react';
import { useTheme } from 'next-themes';
import { useSyncExternalStore } from 'react';

import { cn } from '@/lib/utils';

const subscribe = () => () => undefined;
const getSnapshot = () => true;
const getServerSnapshot = () => false;

export function ThemeToggle() {
  const { resolvedTheme, setTheme } = useTheme();
  const mounted = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
  const isDark = mounted && resolvedTheme === 'dark';

  return (
    <button
      type="button"
      role="switch"
      aria-checked={isDark}
      aria-label={isDark ? 'Switch to light mode' : 'Switch to dark mode'}
      disabled={!mounted}
      className={cn(
        'relative inline-flex h-9 w-[68px] shrink-0 items-center rounded-pill border border-border bg-surface-muted p-1 transition duration-180 ease-brand',
        'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
        'disabled:opacity-60',
      )}
      onClick={() => setTheme(isDark ? 'light' : 'dark')}
    >
      <span className="pointer-events-none absolute inset-y-0 left-0 flex w-1/2 items-center justify-center" aria-hidden="true">
        <Sun className={cn('h-3.5 w-3.5 transition', isDark ? 'text-muted-foreground' : 'text-warning')} />
      </span>
      <span className="pointer-events-none absolute inset-y-0 right-0 flex w-1/2 items-center justify-center" aria-hidden="true">
        <Moon className={cn('h-3.5 w-3.5 transition', isDark ? 'text-info' : 'text-muted-foreground')} />
      </span>
      <span
        aria-hidden="true"
        className={cn(
          'relative z-10 grid h-7 w-7 place-items-center rounded-full bg-primary text-white shadow-sm transition duration-180 ease-brand',
          isDark ? 'translate-x-[30px]' : 'translate-x-0',
        )}
      >
        {isDark ? <Moon className="h-3.5 w-3.5" /> : <Sun className="h-3.5 w-3.5" />}
      </span>
    </button>
  );
}
