'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { AuthProvider, useAuth } from '@/components/AuthProvider'
import NavBar from '@/components/NavBar'
import TabBar from '@/components/TabBar'
import CheckInCard from '@/components/CheckInCard'
import { listItems, getStreak, getTodayStatus, type ICheckInItem } from '@/services/checkin'

function Dashboard() {
  const { user, loading } = useAuth()
  const router = useRouter()
  const [items, setItems] = useState<ICheckInItem[]>([])
  const [streaks, setStreaks] = useState<Record<string, number>>({})
  const [todayStatus, setTodayStatus] = useState<Record<string, boolean>>({})
  const [pageLoading, setPageLoading] = useState(true)

  useEffect(() => {
    if (!loading && !user) {
      router.push('/login')
      return
    }
    if (user) loadItems()
  }, [user, loading, router])

  async function loadItems() {
    try {
      const [itemList, status] = await Promise.all([listItems(), getTodayStatus()])
      setItems(itemList)
      setTodayStatus(status)
      const s: Record<string, number> = {}
      await Promise.all(itemList.map(async (item) => {
        try {
          const { streak } = await getStreak(item.id)
          s[item.id] = streak
        } catch { /* ignore */ }
      }))
      setStreaks(s)
    } catch { /* ignore */ }
    setPageLoading(false)
  }

  const activeItems = items.filter(i => i.status === 'active')
  const pausedItems = items.filter(i => i.status === 'paused')

  if (loading || pageLoading) return <div style={{ padding: 40, textAlign: 'center', color: '#86868B' }}>加载中...</div>
  if (!user) return null

  return (
    <>
      <NavBar title="寸进" showLogout />

      <div className="card" style={{ marginTop: 16, display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 22,
          background: 'linear-gradient(135deg, #FF6B35, #FF4D6D)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 18, color: 'white', fontWeight: 600, flexShrink: 0,
        }}>
          {user.nickname?.[0] || user.phone?.slice(-4) || '?'}
        </div>
        <div style={{ flex: 1 }}>
          <p style={{ fontSize: 16, fontWeight: 600 }}>{user.nickname || '用户'}</p>
          <p style={{ fontSize: 13, color: '#86868B' }}>积分 {user.points} · {activeItems.length} 个活跃项</p>
        </div>
        <button onClick={() => router.push('/profile')}
          style={{ background: 'none', border: 'none', fontSize: 14, color: '#FF6B35', cursor: 'pointer' }}>
          我的
        </button>
      </div>

      <div style={{ padding: '20px 16px 8px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h2 style={{ fontSize: 20, fontWeight: 700 }}>今日打卡</h2>
        <button onClick={() => router.push('/checkin/create')}
          style={{
            padding: '6px 14px', borderRadius: 8, border: '1.5px solid #FF6B35',
            background: 'white', color: '#FF6B35', fontSize: 14, fontWeight: 600, cursor: 'pointer',
          }}>
          + 创建
        </button>
      </div>

      {activeItems.length === 0 ? (
        <div className="card" style={{ textAlign: 'center', padding: '40px 16px' }}>
          <p style={{ fontSize: 40, marginBottom: 12 }}>📋</p>
          <p style={{ fontSize: 15, color: '#86868B' }}>
            还没有打卡项<br />
            <span style={{ fontSize: 13 }}>点击右上角"创建"开始你的成长之旅</span>
          </p>
        </div>
      ) : (
        activeItems.map(item => (
          <CheckInCard key={item.id} item={item} streak={streaks[item.id]}
            isDone={todayStatus[item.id]}
            onCheckIn={(id) => setTodayStatus(s => ({ ...s, [id]: true }))} />
        ))
      )}

      {pausedItems.length > 0 && (
        <>
          <h3 style={{ fontSize: 15, color: '#86868B', padding: '20px 16px 4px' }}>已暂停 ({pausedItems.length})</h3>
          {pausedItems.map(item => (
            <CheckInCard key={item.id} item={item} />
          ))}
        </>
      )}

      <div style={{ height: 100 }} />
      <TabBar />
    </>
  )
}

export default function HomePage() {
  return (
    <AuthProvider>
      <Dashboard />
    </AuthProvider>
  )
}
