"use client";

require("../polyfill");

import { useState, useEffect } from "react";

import styles from "./home.module.scss";

import BotIcon from "../icons/bot.svg";
import loadingIcon from "../icons/loading.gif";

import { getCSSVar, useMobileScreen } from "../utils";

import dynamic from "next/dynamic";
import { Path, SlotID } from "../constant";
import { ErrorBoundary } from "./error";

import { getISOLang, getLang } from "../locales";

import {
  HashRouter as Router,
  Routes,
  Route,
  useLocation,
} from "react-router-dom";
import { SideBar } from "./sidebar";
import { useAppConfig } from "../store/config";
import { AuthPage } from "./auth";
import { getClientConfig } from "../config/client";
import { type ClientApi, getClientApi } from "../client/api";
import { useAccessStore } from "../store";

export function Loading() {
  /** second版本注释掉进度条 */
  // const [progress, setProgress] = useState(1);
  //
  // useEffect(() => {
  //   let isMounted = true;
  //
  //   const intervalId = setInterval(() => {
  //     if (isMounted && progress < 100) {
  //       // 每隔一段时间增加1%进度
  //       setProgress(prevProgress => prevProgress + 1);
  //     }
  //   }, 30);// 每10毫秒更新1%进度
  //
  //   return () => {
  //     isMounted = false;
  //     clearInterval(intervalId);
  //   };
  // }, [progress]);

  return (
    <div className={styles["loading-content"] + " no-dark"}>
      <img src={loadingIcon.src} />
      {/* seceond版本注释掉进度条 */}
      {/* <div style={{ width: '60%', height: 15, background: '#F5F6F9', borderRadius: 8, marginTop: '20%', position: 'relative' }}> */}
      {/*   <div */}
      {/*     style={{ */}
      {/*       width: `${progress}%`, */}
      {/*       height: 15, */}
      {/*       background: '#265C7D', */}
      {/*       borderRadius: 8, */}
      {/*       display: 'flex', */}
      {/*       justifyContent: 'flex-end', */}
      {/*       alignItems: 'center', */}
      {/*       position: 'absolute' */}
      {/*     }} */}
      {/*   > */}
      {/*     <div style={{ color: '#FFFFFF', fontSize: 12, lineHeight: 12, marginRight: 4 }}> */}
      {/*       {progress}% */}
      {/*     </div> */}
      {/*   </div> */}
      {/* </div> */}
    </div>
  );
}

// 延时器
export const delayer = (): Promise<any> => {
  // 延时时间-秒
  const time: number = 0.1;
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({});
    }, time * 1000);
  });
}

const Artifacts = dynamic(
  async () => {
    await delayer();
    return (await import("./artifacts")).Artifacts
  },
  {
    loading: () => <Loading />,
  }
);

const Settings = dynamic(
  async () => {
    await delayer();
    return (await import("./settings")).Settings
  },
  {
    loading: () => <Loading />,
  }
);

const Chat = dynamic(
  async () => {
    await delayer();
    return (await import("./chat")).Chat
  },
  {
    loading: () => <Loading />,
  }
);

const Record = dynamic(
  async () => {
    await delayer();
    return (await import("./Record"))
  },
  {
    loading: () => <Loading />,
  }
);

const DeekSeek = dynamic(
  async () => {
    return (await import("./DeekSeek"))
  },
  {
    loading: () => <Loading />,
  }
);

const NewChat = dynamic(
  async () => {
    await delayer();
    return (await import("./new-chat")).NewChat
  },
  {
    loading: () => <Loading />,
  }
);

const MaskPage = dynamic(
  async () => {
    await delayer();
    return (await import("./mask")).MaskPage
  },
  {
    loading: () => <Loading />,
  }
);

const Sd = dynamic(
  async () => {
    await delayer();
    return (await import("./sd")).Sd
  },
  {
    loading: () => <Loading />,
  }
);

export function useSwitchTheme() {
  const config = useAppConfig();

  useEffect(() => {
    document.body.classList.remove("light");
    document.body.classList.remove("dark");

    if (config.theme === "dark") {
      document.body.classList.add("dark");
    } else if (config.theme === "light") {
      document.body.classList.add("light");
    }

    const metaDescriptionDark = document.querySelector(
      'meta[name="theme-color"][media*="dark"]',
    );
    const metaDescriptionLight = document.querySelector(
      'meta[name="theme-color"][media*="light"]',
    );

    if (config.theme === "auto") {
      metaDescriptionDark?.setAttribute("content", "#151515");
      metaDescriptionLight?.setAttribute("content", "#fafafa");
    } else {
      const themeColor = getCSSVar("--theme-color");
      metaDescriptionDark?.setAttribute("content", themeColor);
      metaDescriptionLight?.setAttribute("content", themeColor);
    }
  }, [config.theme]);
}

function useHtmlLang() {
  useEffect(() => {
    const lang = getISOLang();
    const htmlLang = document.documentElement.lang;

    if (lang !== htmlLang) {
      document.documentElement.lang = lang;
    }
  }, []);
}

const useHasHydrated = () => {
  const [hasHydrated, setHasHydrated] = useState<boolean>(false);

  useEffect(() => {
    setHasHydrated(true);
  }, []);

  return hasHydrated;
};

const loadAsyncGoogleFont = () => {
  const linkEl = document.createElement("link");
  const proxyFontUrl = "/google-fonts";
  const remoteFontUrl = "https://fonts.googleapis.com";
  const googleFontUrl =
    getClientConfig()?.buildMode === "export" ? remoteFontUrl : proxyFontUrl;
  linkEl.rel = "stylesheet";
  linkEl.href =
    googleFontUrl +
    "/css2?family=" +
    encodeURIComponent("Noto Sans:wght@300;400;700;900") +
    "&display=swap";
  document.head.appendChild(linkEl);
};

export function WindowContent(props: { children: React.ReactNode }) {
  return (
    <div className={styles["window-content"]} id={SlotID.AppBody}>
      {props?.children}
    </div>
  );
}

function Screen() {
  const config = useAppConfig();
  const location = useLocation();
  const isArtifact = location.pathname.includes(Path.Artifacts);
  const isHome = location.pathname === Path.Home;
  const isAuth = location.pathname === Path.Auth;
  const isSd = location.pathname === Path.Sd;
  const isSdNew = location.pathname === Path.SdNew;

  const isMobileScreen = useMobileScreen();
  const shouldTightBorder =
    getClientConfig()?.isApp || (config.tightBorder && !isMobileScreen);

  useEffect(() => {
    loadAsyncGoogleFont();
  }, []);

  if (isArtifact) {
    return (
      <Routes>
        <Route path="/artifacts/:id" element={<Artifacts />} />
      </Routes>
    );
  }
  const renderContent = () => {
    if (isAuth) return <AuthPage />;
    if (isSd) return <Sd />;
    if (isSdNew) return <Sd />;
    return (
      <>
        {
          location.pathname === '/deepSeek' ?
            <>
              <WindowContent>
                <Routes>
                  <Route path='/deepSeek' element={<DeekSeek />} />
                </Routes>
              </WindowContent>
            </>
            :
            <>
              <SideBar className={isHome ? styles["sidebar-show"] : ""} />
              <WindowContent>
                <Routes>
                  <Route path={Path.Home} element={<Chat />} />
                  {/* <Route path={'/record'} element={<Record />} /> */}
                  {/* <Route path={Path.NewChat} element={<NewChat />} /> */}
                  {/* <Route path={Path.Masks} element={<MaskPage />} /> */}
                  <Route path={Path.Chat} element={<Chat />} />
                  {/* <Route path={Path.Settings} element={<Settings />} /> */}
                </Routes>
              </WindowContent>
            </>
        }
      </>
    );
  };

  return (
    <div
      className={`${styles.container} ${shouldTightBorder ? styles["tight-container"] : styles.container
        } ${getLang() === "ar" ? styles["rtl-screen"] : ""}`}
    >
      {renderContent()}
    </div>
  );
}

export function useLoadData() {
  const config = useAppConfig();

  const api: ClientApi = getClientApi(config.modelConfig.providerName);

  useEffect(() => {
    (async () => {
      const models = await api.llm.models();
      config.mergeModels(models);
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
}

export function Home() {
  useSwitchTheme();
  useLoadData();
  useHtmlLang();

  useEffect(() => {
    // console.log("[Config] got config from build time", getClientConfig());
    useAccessStore.getState().fetch();
  }, []);

  if (!useHasHydrated()) {
    return <Loading />;
  }

  return (
    <ErrorBoundary>
      <Router>
        <Screen />
      </Router>
    </ErrorBoundary>
  );
}
