import { createRoot } from 'react-dom/client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { RouterProvider } from 'react-router-dom'
import { ConfigProvider, App as AntApp, theme } from 'antd'
import zhCN from 'antd/locale/zh_CN'
import { router } from './router'
import { ErrorBoundary } from './components/ErrorBoundary'
import { useThemeStore } from './stores/themeStore'
import './styles/globals.css'

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: 1,
      refetchOnWindowFocus: false,
      staleTime: 30_000,
    },
  },
})

function ThemedApp() {
  const resolved = useThemeStore((s) => s.resolved)

  return (
    <ConfigProvider
      locale={zhCN}
      theme={{
        token: {
          colorPrimary: '#863bff',
          colorBgContainer: resolved === 'dark' ? '#292524' : '#ffffff',
          colorBgElevated: resolved === 'dark' ? '#1c1917' : '#ffffff',
          colorBgLayout: resolved === 'dark' ? '#0c0a09' : '#fafaf9',
          colorBorder: resolved === 'dark' ? '#44403c' : '#e7e5e4',
          colorBorderSecondary: resolved === 'dark' ? '#44403c' : '#f5f5f4',
          colorText: resolved === 'dark' ? '#fafaf9' : '#1c1917',
          colorTextSecondary: resolved === 'dark' ? '#a8a29e' : '#78716c',
          colorTextTertiary: resolved === 'dark' ? '#78716c' : '#a8a29e',
          borderRadius: 8,
          borderRadiusLG: 12,
          fontFamily:
            '"Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
          fontSize: 14,
          controlHeight: 36,
        },
        algorithm: resolved === 'dark' ? theme.darkAlgorithm : theme.defaultAlgorithm,
        components: {
          Card: {
            borderRadiusLG: 12,
          },
          Table: {
            borderRadiusLG: 12,
            headerBg: resolved === 'dark' ? '#1c1917' : '#fafaf9',
            headerColor: resolved === 'dark' ? '#a8a29e' : '#78716c',
            rowHoverBg: resolved === 'dark' ? 'rgba(134,59,255,0.06)' : 'rgba(134,59,255,0.04)',
          },
          Button: {
            borderRadius: 8,
            controlHeight: 36,
          },
          Input: {
            borderRadius: 8,
          },
          Select: {
            borderRadius: 8,
          },
          Modal: {
            borderRadiusLG: 12,
          },
          Tag: {
            borderRadiusSM: 9999,
          },
        },
      }}
    >
      <AntApp>
        <QueryClientProvider client={queryClient}>
          <RouterProvider router={router} />
        </QueryClientProvider>
      </AntApp>
    </ConfigProvider>
  )
}

createRoot(document.getElementById('root')!).render(
  <ErrorBoundary>
    <ThemedApp />
  </ErrorBoundary>,
)
