import React, { createContext,useContext, useState, useEffect, } from 'react';
import { ConfigProvider, theme } from "antd";
const ThemeContext = createContext();

export const ThemeProvider = ({ children }) => {
  const [isDarkMode, setIsDarkMode] = useState(() => {
    const savedTheme = localStorage.getItem('theme');
    return savedTheme === 'dark' || (savedTheme === null && window.matchMedia('(prefers-color-scheme: dark)').matches);
  });

  useEffect(() => {
    localStorage.setItem('theme', isDarkMode ? 'dark' : 'light');
    document.documentElement.classList.toggle('dark', isDarkMode);
  }, [isDarkMode]);

  const toggleTheme = () => {
    setIsDarkMode(!isDarkMode);
  };

  return (
    <ThemeContext.Provider value={{ isDarkMode, toggleTheme }}>
 <ConfigProvider
      theme={{
        algorithm: isDarkMode ? theme.darkAlgorithm : theme.defaultAlgorithm,
        token: {
          colorPrimary: "#1677ff",
          borderRadius: 4,
          colorBgContainer: isDarkMode ? "#141414" : "#ffffff",
          colorBgElevated: isDarkMode ? "#1f1f1f" : "#ffffff",
          colorText: isDarkMode
            ? "rgba(255, 255, 255, 0.85)"
            : "rgba(0, 0, 0, 0.85)",
          colorTextSecondary: isDarkMode
            ? "rgba(255, 255, 255, 0.45)"
            : "rgba(0, 0, 0, 0.45)",
        },
        components: {
          // 为所有支持 variant 的组件设置 filled 模式
          Form: {
            variant: 'filled',
          },
          Input: {
            variant: 'filled',
          },
          Select: {
            variant: 'filled',
          },
          TreeSelect: {
            variant: 'filled',
          },
          DatePicker: {
            variant: 'filled',
          },
          TimePicker: {
            variant: 'filled',
          },
          Cascader: {
            variant: 'filled',
          },
          AutoComplete: {
            variant: 'filled',
          },
        }
      }}
    >
       { children }
    </ConfigProvider>
    </ThemeContext.Provider>
  );
};

export const useTheme = () => {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};