import ErrorBoundary from '@/components/ErrorBoundary'
import useAuthStore from '@/stores/AuthStore'
import useConversationStore from '@/stores/ConversationStore'
import { useThemeContext } from '@/stores/ThemeContext'
import { App as AntApp, ConfigProvider, Empty, Layout, Typography, theme } from 'antd'
import zhLocale from 'antd/locale/zh_CN'
import 'dayjs/locale/zh-cn'
import { useEffect, useState } from 'react'
import { Outlet, useHref, useNavigate } from 'react-router-dom'

import '@/assets/App.css'
import 'react-chat-elements/dist/main.css'

function AuthApp() {

  const navigate = useNavigate()

  const { colorPrimary, borderRadius } = useThemeContext()
  const loginUser = useAuthStore(state => state.loginUser)

  const href = useHref()

  const [connectWebsocket, fetchInitialData, disconnectWebsocket ] = useConversationStore((state) => [
    state.connectWebsocket,
    state.fetchInitialData,
    state.disconnectWebsocket,
  ]);
  useEffect(() => {
    if (!("Notification" in window)) {
      alert("This browser does not support desktop notification");
      return false;
    } else {
      Notification.requestPermission();
    }
    if (loginUser.userId > 0) {
      connectWebsocket(loginUser.userId);
      fetchInitialData(loginUser.userId); // userIdStr
    }
    return () => {
      disconnectWebsocket();
    };
  }, [])

  useEffect(() => {
    // 除了路由 /p...以外都需要登陆系统
    if ((loginUser.userId === -1) && (href.indexOf('/p/') === -1)) {
      navigate('/p/dingding/qrcode')
    }
	}, [href])

  const {
    token: { colorBgContainer },
  } = theme.useToken()

  return (
    <ConfigProvider
      theme={{
        token: {
          colorPrimary: colorPrimary,
          borderRadius: borderRadius,
          fontFamily: "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,'Noto Sans',sans-serif,'Noto Color Emoji','Apple Color Emoji','Segoe UI Emoji','Segoe UI Symbol'",
        },
        algorithm: theme.defaultAlgorithm,
      }}
      locale={zhLocale}
      renderEmpty={() => <Empty description={false} />}
    >
      <AntApp>
        <ErrorBoundary>
          <Outlet />
        </ErrorBoundary>
      </AntApp>
    </ConfigProvider>
  )
}

export default AuthApp
