import { ConfigProvider, theme } from 'antd';
import React, { useEffect, useState } from 'react';
import { getTheme } from './ThemeSwitcher';

interface ThemeProviderProps {
  children: React.ReactNode;
}

const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
  const [isDark, setIsDark] = useState(getTheme() === 'dark');

  useEffect(() => {
    const handleThemeChange = (e: CustomEvent) => {
      setIsDark(e.detail.theme === 'dark');
    };

    window.addEventListener('theme-change', handleThemeChange as EventListener);
    return () => {
      window.removeEventListener(
        'theme-change',
        handleThemeChange as EventListener,
      );
    };
  }, []);

  return (
    <ConfigProvider
      theme={{
        algorithm: isDark ? theme.darkAlgorithm : theme.defaultAlgorithm,
      }}
    >
      {children}
    </ConfigProvider>
  );
};

export default ThemeProvider;
