import React, { useEffect } from "react";
import { AlertTitle } from "@mui/material";
import MuiAlert from "@mui/material/Alert";
import CssBaseline from "@mui/material/CssBaseline";
import Slide from "@mui/material/Slide";
import Snackbar from "@mui/material/Snackbar";
import * as Sentry from "@sentry/react";
import { Outlet, useModel, useNavigate, useLocation } from "@umijs/max";
import { ConfigProvider } from "antd";
import locale from "antd/locale/zh_CN";
import "dayjs/locale/zh-cn";
import ThemeProvider from "./theme";

// 自定义主题
// const { palette } = useTheme();
// const theme = useMemo(() => {
//   return createTheme(curthemeconfig);
// }, [curthemeconfig]);

{
  /* <div style={{ position: "fixed", right: 36, top: 36 }}>
<IconButton
    onClick={() => {
    if (curthemeconfig.palette.mode == "dark") {
        dispatch(changetheme("lightTheme"));
    } else {
        dispatch(changetheme("darkTheme"));
    }
    }}
>
    {curthemeconfig.palette.mode !== "dark" ? (
    <WbSunnyIcon style={{ color: "#ff9900" }}></WbSunnyIcon>
    ) : (
    <DarkModeIcon></DarkModeIcon>
    )}
</IconButton>
</div>  */
}

Sentry.init({
  dsn: "http://38a2decfe9214e639164d2ca6ef92a67@iot-dev.nangaoyun.com:9000/9",
  integrations: [new Sentry.BrowserTracing(), new Sentry.Replay()],
  enabled: process.env.NODE_ENV !== "development",
  // Set tracesSampleRate to 1.0 to capture 100%
  // of transactions for performance monitoring.
  // We recommend adjusting this value in production
  tracesSampleRate: 1.0,
  // Capture Replay for 10% of all sessions,
  // plus for 100% of sessions with an error
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
});

Sentry.configureScope(function (scope) {
  scope.setLevel("error");
});

const Alert = React.forwardRef(function Alert(props, ref) {
  return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />;
});

function App() {
  const { initialState: { message, fetchUserInfo }, setInitialState } = useModel("@@initialState");
  const navigate = useNavigate();
  const location = useLocation();
  const handleClose = (event) => {
    setInitialState((s) => ({
      ...s,
      message: {
        ...message,
        open: false,
      },
    }));
  };

  // ---------- 初始化时检查 token ----------
  useEffect(() => {
    // 获取 URL 参数
    const url = new URL(window.location.href);
    const token =
      url.searchParams.get('token') ||
      new URLSearchParams(window.location.hash.split('?')[1] || '').get('token');

    if (token) {
      localStorage.setItem("TOKENES", token);
      // ✅ 清理 URL 中的 token 参数
      const newUrl = window.location.origin + '/#' + window.location.hash.split('#')[1];
      window.history.replaceState(null, '', newUrl);
      (async () => {
        try {
          let user = await fetchUserInfo();
          if (user) {
            navigate("/work", { replace: true });
          } else {
            localStorage.clear();
            navigate("/user/login", { replace: true });
          }
        } catch (err) {
          localStorage.clear();
          navigate("/user/login", { replace: true });
        }
      })();
    } else {
      // 没有 token，若不在登录页则跳转
      if (!location.pathname.startsWith("/user")) {
        localStorage.clear();
        navigate("/user/login", { replace: true });
      }
    }
  }, []);
  return (
    <ConfigProvider locale={locale}>
      <ThemeProvider>
        <CssBaseline />
        <Snackbar
          open={message?.open}
          TransitionComponent={(props) => <Slide {...props} direction="left" />}
          {...message?.snackbar}
          onClose={handleClose}
        >
          <Alert
            severity={message?.type}
            onClose={handleClose}
            {...message.alert}
            sx={{ color: "#f9f9f9" }}
          >
            {message?.title ? <AlertTitle>{message?.title}</AlertTitle> : null}
            {message?.content}
          </Alert>
        </Snackbar>
        <Outlet />
      </ThemeProvider>
    </ConfigProvider>
  );
}

export default App;
