import Avatar from '@/components/avatar'
import PageBreadcrumb from '@/components/breadcrumb'
import ErrorPage from '@/components/error/error.tsx'
import SelectLang from '@/components/select-lang'
import { appAtom } from '@/store/system.ts'
import { userMenuDataAtom } from '@/store/system/user.ts'
import { MenuItem } from '@/global'
import { ProConfigProvider, ProLayout, } from '@ant-design/pro-components'
import { zhCNIntl, enUSIntl } from '@ant-design/pro-provider/es/intl'
import { CatchBoundary, Link, Outlet } from '@tanstack/react-router'
import { ConfigProvider } from '@/components/config-provider'
import { useState } from 'react'
import defaultProps from './_defaultProps'
import { useAtomValue } from 'jotai'
import { useStyle } from '@/layout/style.ts'
import zh from 'antd/locale/zh_CN'
import en from 'antd/locale/en_US'

//根据menuData生成Breadcrumb所需的数据
const getBreadcrumbData = (menuData: MenuItem[], pathname: string) => {
  const breadcrumbData: any[] = []
  const findItem = (menuData: any[], pathname: string) => {
    for (let i = 0; i < menuData.length; i++) {
      if (menuData[i].path === pathname) {
        breadcrumbData.push(menuData[i])
        return true
      }
      if (menuData[i].children) {
        if (findItem(menuData[i].children, pathname)) {
          breadcrumbData.push(menuData[i])
          return true
        }
      }
    }
    return false
  }
  findItem(menuData, pathname)
  return breadcrumbData.reverse()
}

export default () => {

  const { styles } = useStyle()
  const { data: menuData = [], isLoading } = useAtomValue(userMenuDataAtom)
  const { language } = useAtomValue(appAtom)
  const items = getBreadcrumbData(menuData, location.pathname)
  const [ pathname, setPathname ] = useState(location.pathname)

  return (
    <div
      className={styles.container}
      id="crazy-pro-layout"
      style={{
        height: '100vh',
        // overflow: 'auto',
      }}
    >
      <CatchBoundary
        getResetKey={() => 'reset-page'}
        errorComponent={ErrorPage}
      >
        <ProConfigProvider hashed={false} intl={language === 'zh-CN' ? zhCNIntl : enUSIntl}>
          <ConfigProvider
            locale={language === 'zh-CN' ? zh : en}
            getTargetContainer={() => {
              return document.getElementById('crazy-pro-layout') || document.body
            }}
          >
            <ProLayout
              headerContentRender={() => <PageBreadcrumb
                className={'top-breadcrumb'}
                showIcon={false}
                items={items}/>}
              title="Crazy Pro"
              {...defaultProps}
              route={{
                path: '/',
                routes: menuData
              }}
              location={{
                pathname,
              }}
              token={{
                header: {
                  colorBgMenuItemSelected: 'rgba(0,0,0,0.04)',
                },
              }}
              menu={{
                collapsedShowGroupTitle: true,
                loading: isLoading,
              }}

              avatarProps={{
                // src: 'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
                render: () => {
                  return (
                    <Avatar/>
                  )
                },
              }}
              actionsRender={(props) => {
                if (props.isMobile) return []
                if (typeof window === 'undefined') return []
                return [
                  <SelectLang/>,
                ]
              }}
              menuProps={{
                className: styles.sideMenu,
              }}
              menuRender={(_, defaultDom) => (
                <span style={{ userSelect: 'none' }}>
                  {defaultDom}
                </span>
              )}
              menuItemRender={(item, dom) => {
                return <span style={{ userSelect: 'none' }} onClick={() => {
                  setPathname(item.path || '/dashboard')
                }}
                >
                  <Link to={item.path} target={item.type === 'url' ? '_blank' : '_self'}>
                    {dom}
                  </Link>
                </span>
              }}
              {...{
                'layout': 'mix',
                'navTheme': 'light',
                'contentWidth': 'Fluid',
                'fixSiderbar': true,
                // 'colorPrimary': '#1677FF',
                'siderMenuType': 'group',
                // layout: 'side',
              }}
            >
              <Outlet/>
            </ProLayout>
          </ConfigProvider>
        </ProConfigProvider>
      </CatchBoundary>
    </div>
  )
}
