'use client';
import { useEffect, useState, type ComponentProps } from 'react';
import { ThemeProvider as NextThemesProvider } from 'next-themes';
import { Moon, Sun } from 'lucide-react';
import { useTheme } from 'next-themes';
import { Button } from '@/components/ui';
import { cn } from '@/lib/utils';

const ThemeProvider = ({
  children,
  ...props
}: ComponentProps<typeof NextThemesProvider>) => {
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) return null;
  return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
};

type ThemeToggleProps = {
  size?: number;
  buttonProps?: Omit<ComponentProps<typeof Button>, 'onClick'>;
};

const ThemeToggle = ({ size = 1, buttonProps }: ThemeToggleProps) => {
  const { setTheme, resolvedTheme } = useTheme();
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) {
    return (
      <Button {...buttonProps}>
        <span style={{ height: `${size}rem`, width: `${size}rem` }} />
      </Button>
    );
  }

  const toggleTheme = () => {
    if (resolvedTheme === 'dark') setTheme('light');
    else setTheme('dark');
  };

  return (
    <Button
      variant='outline'
      size='icon'
      {...buttonProps}
      onClick={toggleTheme}
      className={cn('cursor-pointer', buttonProps?.className)}
    >
      <Sun
        style={{ height: `${size}rem`, width: `${size}rem` }}
        className='rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0'
      />
      <Moon
        style={{ height: `${size}rem`, width: `${size}rem` }}
        className='absolute rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100'
      />
    </Button>
  );
};

export { ThemeProvider, ThemeToggle, type ThemeToggleProps };
