import { Text, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import { backend, type BackendExpertBooking } from '@/api/backend'
import { EmptyState, Page, StatusSide } from '@/components/ui'
import { ensureLoggedIn, getToken } from '@/stores/storage'

function statusLabel(status: BackendExpertBooking['status']) {
  if (status === 'pending_payment') return '待支付'
  if (status === 'pending_expert') return '待专家确认'
  if (status === 'confirmed') return '预约中'
  if (status === 'pending_user_confirm') return '待确认完成'
  if (status === 'disputed') return '争议处理中'
  if (status === 'completed') return '已完成'
  if (status === 'rejected') return '已拒绝'
  return '已取消'
}

function formatTime(value?: string) {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return '-'
  return `${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

export default function ExpertBookingsPage() {
  const [items, setItems] = useState<BackendExpertBooking[]>([])
  const [loading, setLoading] = useState(false)

  useDidShow(() => {
    const user = ensureLoggedIn('/pages/account/expert-bookings/index')
    const token = getToken()
    if (!user || !token) return
    setLoading(true)
    backend.accountExpertBookings(token)
      .then((result) => setItems(result.items.filter((item) => item.userId === user.id)))
      .catch((error) => Taro.showToast({ title: error instanceof Error ? error.message : '专家预约加载失败', icon: 'none' }))
      .finally(() => setLoading(false))
  })

  return (
    <Page title="专家预约" subtle={loading ? '正在同步专家预约' : `当前 ${items.length} 条`}>
      {items.length === 0 && !loading ? <EmptyState title="暂无专家预约" text="在专家主页提交预约并支付后，预约状态会在这里展示。" /> : (
        <View className="list-shell">
          {items.map((item) => (
            <View key={item.id} className="list-line" onClick={() => Taro.navigateTo({ url: `/pages/account/expert-bookings/detail/index?id=${encodeURIComponent(item.id)}` })}>
              <View className="list-main">
                <Text className="row-title">{item.expert.name} 专家咨询</Text>
                <Text className="row-sub">{item.bookingNo} · {formatTime(item.startsAt)}</Text>
                <View className="meta-grid compact">
                  <View><Text className="meta-label">专家机构</Text><Text className="meta-value">{item.expert.organization || '-'}</Text></View>
                  <View><Text className="meta-label">问题摘要</Text><Text className="meta-value">{item.question || item.background || '-'}</Text></View>
                </View>
              </View>
              <StatusSide value={statusLabel(item.status)} orange={item.status === 'confirmed' || item.status === 'pending_user_confirm'} />
            </View>
          ))}
        </View>
      )}
    </Page>
  )
}
