import { THEME_KEY } from '@/constants';
import { MoonOutlined, SunOutlined } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import { Segmented } from 'antd';
import React, { useEffect, useState } from 'react';

export interface ThemeSwitcherProps {
  className?: string;
}

const ThemeSwitcher: React.FC<ThemeSwitcherProps> = ({ className }) => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [isDark, setIsDark] = useState(
    (initialState?.theme as 'light' | 'dark') === '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,
      );
    };
  }, []);

  const handleThemeChange = (newTheme: 'light' | 'dark') => {
    // Check if browser supports View Transitions API
    const supportsViewTransition = 'startViewTransition' in document;

    if (!supportsViewTransition) {
      // Fallback: just change theme without animation
      localStorage.setItem(THEME_KEY, newTheme);
      setIsDark(newTheme === 'dark');
      window.dispatchEvent(
        new CustomEvent('theme-change', { detail: { theme: newTheme } }),
      );
      setInitialState({
        ...initialState,
        theme: newTheme,
      } as any);
      return;
    }

    // Set origin to top-right corner
    const x = window.innerWidth;
    const y = 0;

    // Calculate end radius to cover the entire screen
    const endRadius = Math.hypot(
      Math.max(x, window.innerWidth - x),
      Math.max(y, window.innerHeight - y),
    );

    // Start the view transition
    const transition = (document as any).startViewTransition(() => {
      localStorage.setItem(THEME_KEY, newTheme);
      setIsDark(newTheme === 'dark');
      window.dispatchEvent(
        new CustomEvent('theme-change', { detail: { theme: newTheme } }),
      );
    });

    // Animate the ripple effect
    transition.ready.then(() => {
      requestAnimationFrame(() => {
        document.documentElement.animate(
          {
            clipPath: [
              `circle(0px at ${x}px ${y}px)`,
              `circle(${endRadius}px at ${x}px ${y}px)`,
            ],
          },
          {
            duration: 800,
            easing: 'ease-in-out',
            pseudoElement: '::view-transition-new(root)',
          },
        );
      });
    });

    // Update initialState after transition
    setInitialState({
      ...initialState,
      theme: newTheme,
    } as any);
  };

  return (
    <Segmented
      className={className}
      size="small"
      shape="round"
      value={isDark ? 'dark' : 'light'}
      onChange={(value) => handleThemeChange(value as 'light' | 'dark')}
      options={[
        { value: 'light', icon: <SunOutlined /> },
        { value: 'dark', icon: <MoonOutlined /> },
      ]}
    />
  );
};

export default ThemeSwitcher;

// Helper function để get theme từ localStorage
export const getTheme = (): 'light' | 'dark' => {
  return (localStorage.getItem(THEME_KEY) as 'light' | 'dark') || 'light';
};
