'use client';
import { Button } from '@/components/ui/button';
import { useCallback, useEffect, useState } from 'react';
import { LuSunMedium, LuMoonStar } from 'react-icons/lu';

export function ThemeToggle() {
  const [theme, setTheme] = useState('light');
  const [isTransitioning, setIsTransitioning] = useState(false);

  useEffect(() => {
    const savedTheme = localStorage.getItem('theme') ?? 'light';
    setTheme(savedTheme);
  }, []);

  const handleToggle = useCallback(() => {
    setIsTransitioning(true);
    setTimeout(() => {
      const newTheme = theme === 'light' ? 'dark' : 'light';
      setTheme(newTheme);

      const computedStyle = getComputedStyle(document.documentElement);
      const currentBackground = computedStyle.getPropertyValue('--color-background').trim();
      const currentText = computedStyle.getPropertyValue('--color-text').trim();

      localStorage.setItem('theme', newTheme);
      document.documentElement.style.setProperty('--color-background', currentText);
      document.documentElement.style.setProperty('--color-text', currentBackground);

      setTimeout(() => {
        setIsTransitioning(false);
      }, 150);
    }, 150);
  }, [theme]);

  return (
    <Button variant='ghost' size='icon' onClick={handleToggle} className='relative overflow-hidden'>
      <div className='relative w-6 h-6'>
        <div
          className={`absolute inset-0 transform transition-all duration-300 ${
            isTransitioning ? 'opacity-0 scale-50 rotate-90' : 'opacity-100 scale-100 rotate-0'
          }`}
        >
          {theme === 'dark' ? <LuSunMedium className='!h-6 !w-6' /> : <LuMoonStar className='!h-6 !w-6' />}
        </div>
      </div>
      <span className='sr-only'>Toggle theme</span>
    </Button>
  );
}
