/**
 * 首頁 - 檢查系統初始化狀態後導向
 *
 * 流程：
 * 1. 檢查系統是否已初始化
 * 2. 如果未初始化 → 導向 /installation
 * 3. 如果已初始化 → 檢查登入狀態
 *    - 已登入 → /dashboard
 *    - 未登入 → /auth/signin
 */
'use client'

import { useSession } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'

export default function Home() {
  const { data: session, status } = useSession()
  const router = useRouter()
  const [systemChecked, setSystemChecked] = useState(false)
  const [systemInitialized, setSystemInitialized] = useState(false)

  // 第一步：檢查系統初始化狀態
  useEffect(() => {
    checkSystemStatus()
  }, [])

  // 第二步：根據初始化狀態和登入狀態決定導向
  useEffect(() => {
    if (!systemChecked) {
      return // 尚未檢查完成，等待
    }

    // 如果系統未初始化，直接導向初始化頁面
    if (!systemInitialized) {
      console.log('[Home] System not initialized, redirecting to /installation')
      router.push('/installation')
      return
    }

    // 系統已初始化，檢查登入狀態
    const logMsg = `[Home] Status: ${status}, Has session: ${!!session}, Has user: ${!!session?.user}, Email: ${session?.user?.email || 'N/A'}`
    console.log(logMsg)

    // 存到 sessionStorage 以便 debug
    const logs = sessionStorage.getItem('auth_logs') || ''
    sessionStorage.setItem('auth_logs', logs + '\n' + new Date().toISOString() + ' - ' + logMsg)

    // 等待 session 載入完成後再導向
    if (status === 'loading') {
      console.log('[Home] Still loading, waiting...')
      return // 仍在載入中,不做任何動作
    }

    if (status === 'authenticated' && session?.user) {
      console.log('[Home] ✅ Authenticated, redirecting to dashboard')
      sessionStorage.setItem('auth_logs', sessionStorage.getItem('auth_logs') + '\n✅ REDIRECTING TO DASHBOARD')
      router.push('/dashboard')
    } else if (status === 'unauthenticated') {
      console.log('[Home] ❌ Unauthenticated, redirecting to signin')
      sessionStorage.setItem('auth_logs', sessionStorage.getItem('auth_logs') + '\n❌ REDIRECTING TO SIGNIN')
      router.push('/auth/signin')
    } else {
      console.log('[Home] ⚠️ Unexpected state - status:', status, 'has session:', !!session)
    }
  }, [systemChecked, systemInitialized, status, session, router])

  const checkSystemStatus = async () => {
    try {
      const response = await fetch('http://10.1.0.245:10181/api/v1/installation/check-status')

      if (!response.ok) {
        console.error('[Home] Failed to check system status:', response.statusText)
        // 如果無法連接後端，假設未初始化
        setSystemInitialized(false)
        setSystemChecked(true)
        return
      }

      const data = await response.json()
      console.log('[Home] System status:', data)
      setSystemInitialized(data.is_initialized || false)
    } catch (error) {
      console.error('[Home] Error checking system status:', error)
      // 連接錯誤，假設未初始化
      setSystemInitialized(false)
    } finally {
      setSystemChecked(true)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100">
      <div className="text-center">
        <div className="w-16 h-16 border-4 border-indigo-600 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
        <h1 className="text-2xl font-bold text-gray-900 mb-2">HR Portal</h1>
        <p className="text-gray-600">載入中...</p>
        {status && <p className="text-xs text-gray-400 mt-2">狀態: {status}</p>}
      </div>
    </div>
  )
}
