'use client'

import NotionPage from '@/components/NotionPage'
import { siteConfig } from '@/lib/config'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import DashboardBody from '../components/ui/dashboard/DashboardBody'
import DashboardHeader from '../components/ui/dashboard/DashboardHeader'
import CONFIG from '../config'

/**
 * 首頁
 * 重新導向到指定的文章詳情頁
 */
const LayoutIndex = props => {
  const router = useRouter()
  const index = siteConfig('GITBOOK_INDEX_PAGE', 'about', CONFIG)
  const [hasRedirected, setHasRedirected] = useState(false) // 用來追蹤是否已重新導向

  useEffect(() => {
    const tryRedirect = async () => {
      if (!hasRedirected) {
        // 僅在尚未導向時執行
        setHasRedirected(true)

        // 重新導向至指定文章
        await router.push(index)

        // 使用 setTimeout 檢查頁面載入狀態
        setTimeout(() => {
          const article = document.querySelector(
            '#article-wrapper #notion-article'
          )
          if (!article) {
            console.log('請檢查您的 Notion 資料庫中是否包含此 slug 頁面： ', index)

            // 顯示錯誤訊息
            const containerInner = document.querySelector(
              '#theme-gitbook #container-inner'
            )
            const newHTML = `<h1 class="text-3xl pt-12 dark:text-gray-300">設定錯誤</h1><blockquote class="notion-quote notion-block-ce76391f3f2842d386468ff1eb705b92"><div>請在您的 Notion 中新增一篇 slug 為 ${index} 的文章</div></blockquote>`
            containerInner?.insertAdjacentHTML('afterbegin', newHTML)
          }
        }, 2000)
      }
    }

    if (index) {
      console.log('重新導向', index)
      tryRedirect()
    } else {
      console.log('未重新導向', index)
    }
  }, [index, hasRedirected, router])

  return null
}

/**
 * 文章列表
 * 主要依靠頁面導覽
 */
const LayoutPostList = () => {
  return <></>
}

/**
 * 文章搜尋頁
 * 主要依靠頁面導覽
 */
const LayoutSearch = () => {
  return <></>
}

/**
 * 儀表板
 */
const LayoutDashboard = props => {
  const { post } = props

  return (
    <>
      <div className='container grow'>
        <div className='flex flex-wrap justify-center -mx-4'>
          <div id='container-inner' className='w-full p-4'>
            {post && (
              <div id='article-wrapper' className='mx-auto'>
                <NotionPage {...props} />
              </div>
            )}
          </div>
        </div>
      </div>
      {/* 儀表板 */}
      <DashboardHeader />
      <DashboardBody />
    </>
  )
}

export { LayoutDashboard, LayoutIndex, LayoutPostList, LayoutSearch }
