import React, {useContext, useState, useEffect} from 'react';
import type {IRouteComponentProps} from '@umijs/types';
import {context, Link} from 'dumi/theme';
import Navbar from './components/Navbar';
import SideMenu from './components/SideMenu';
import SlugList from './components/SlugList';
import SearchBar from './components/SearchBar';
import ThemeIcon from './components/ThemeIcon';
import './style/layout.less';
import {LLWebsiteRecords, Dropdown, Avatar, Menu} from '@/index';

import themeSwitcher from 'theme-switcher';

const timestamp = new Date().getTime();
const themeMap = {
  dark: `/dark.css?${timestamp}`
  // light: `/light.css?${timestamp}`,
};
const themeConfig = {
  themeMap
};
const {switcher} = themeSwitcher(themeConfig);

const Layout: React.FC<IRouteComponentProps> = ({children, location}) => {
  const isHome = location.pathname === '/';
  const componentPage = /^\/?components/.test(location.pathname);
  const {
    config: {mode, repository},
    meta,
    locale
  } = useContext(context);
  const {url: repoUrl, branch, platform} = repository;
  const [menuCollapsed, setMenuCollapsed] = useState<boolean>(true);
  const isSiteMode = mode === 'site';
  const showHero = isSiteMode && meta.hero;
  const showFeatures = isSiteMode && meta.features;
  const showSideMenu = meta.sidemenu !== false && !showHero && !showFeatures && !meta.gapless;
  const showSlugs =
    !showHero &&
    !showFeatures &&
    Boolean(meta.slugs?.length) &&
    (meta.toc === 'content' || meta.toc === undefined) &&
    !meta.gapless;
  const isCN = /^zh|cn$/i.test(locale);
  const updatedTimeIns = new Date(meta.updatedTime);
  const updatedTime: any = `${updatedTimeIns.toLocaleDateString([], {
    hour12: false
  })} ${updatedTimeIns.toLocaleTimeString([], {hour12: false})}`;
  const repoPlatform =
    {github: 'GitHub', gitlab: 'GitLab'}[
      (repoUrl || '').match(/(github|gitlab)/)?.[1] || 'nothing'
    ] || platform;

  const [theme, setTheme] = useState<string>(
    document.documentElement.getAttribute('data-prefers-color')
  );
  useEffect(() => {
    document.documentElement.setAttribute('data-prefers-color', !componentPage ? 'dark' : theme);
  }, [componentPage, theme]);

  useEffect(() => {
    if (typeof window === 'undefined') {
      return;
    }
    switcher({
      theme,
      useStorage: false
    });
  }, [theme]);

  return (
    <div
      className={`__dumi-default-layout ${isHome ? '__dumi-default-active' : ''}`}
      data-route={location.pathname}
      data-show-sidemenu={String(showSideMenu)}
      data-show-slugs={String(showSlugs)}
      data-site-mode={isSiteMode}
      data-gapless={String(!!meta.gapless)}
      onClick={() => {
        if (menuCollapsed) return;
        setMenuCollapsed(true);
      }}
    >
      <Navbar
        location={location}
        navPrefix={<SearchBar />}
        onMobileMenuClick={ev => {
          setMenuCollapsed(val => !val);
          ev.stopPropagation();
        }}
      />

      <SideMenu mobileMenuCollapsed={menuCollapsed} location={location} />

      {showSlugs && <SlugList slugs={meta.slugs} />}

      <div className="__dumi-default-layout-content">
        {children}

        {!showHero && !showFeatures && meta.filePath && !meta.gapless && (
          <div className="__dumi-default-layout-footer-meta">
            {repoPlatform && (
              <Link to={`${repoUrl}/edit/${branch}/${meta.filePath}`}>
                {isCN ? `在 ${repoPlatform} 上编辑此页` : `Edit this doc on ${repoPlatform}`}
              </Link>
            )}
            <span data-updated-text={isCN ? '最后更新时间：' : 'Last update: '}>{updatedTime}</span>
          </div>
        )}
        {componentPage && (
          <div className="fixed-widgets">
            <Dropdown
              overlay={
                <Menu
                  onClick={({key}) => {
                    setTheme(key);
                  }}
                  selectedKeys={[theme]}
                >
                  {[
                    {type: 'dark', text: '暗色版本'},
                    {type: 'light', text: '亮色版本'}
                  ].map(({type, text}) => (
                    <Menu.Item key={type}>{text}</Menu.Item>
                  ))}
                </Menu>
              }
              placement="topCenter"
            >
              <Avatar className="fixed-widgets-avatar" size={44} icon={<ThemeIcon />} />
            </Dropdown>
          </div>
        )}
        <div className="__dumi-default-layout-footer-records">
          <LLWebsiteRecords
            text="浙ICP备20003028号"
            href="https://beian.miit.gov.cn/"
            infos={['Made by iFLYTEK IUCD & IFEC']}
          />
          <div>
            任颖 / 李俊 &nbsp;&nbsp;&nbsp; 丁禹 / 胡浩 / 蒋华莹 / 吕静 / 柳嘉明 / 厉震宇 / 马月 /
            裘盈 / 王怡翔 / 吴博文 / 徐柯 / 张彬 / 张阳 &nbsp;&nbsp;&nbsp; 特别鸣谢 万杉杉 / 常华伟
          </div>
        </div>
      </div>
    </div>
  );
};

export default Layout;
