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

function statusLabel(status: BackendConsultingRequest['status']) {
  if (status === 'completed') return '已完成'
  if (status === 'in_service') return '服务中'
  if (status === 'pending_payment') return '待支付'
  if (status === 'proposal_ready') return '待确认报价'
  if (status === 'planning') return '方案中'
  if (status === 'communicating') return '沟通中'
  if (status === 'assigned') return '已接单'
  if (status === 'cancelled') return '已取消'
  return '待受理'
}

function submitTime(value?: string) {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return '-'
  return date.toLocaleString('zh-CN')
}

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

  useDidShow(() => {
    const user = ensureLoggedIn('/pages/account/consulting/index')
    const token = getToken()
    if (!user || !token) return
    setLoading(true)
    backend.accountConsultingRequests(token)
      .then((result) => setItems(result.items))
      .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/consulting/detail/index?id=${item.id}` })}>
              <View className="list-main">
                <Text className="row-title">{item.company || item.direction}</Text>
                <View className="meta-grid">
                  <View><Text className="meta-label">提交编号</Text><Text className="meta-value">{item.requestNo}</Text></View>
                  <View><Text className="meta-label">提交时间</Text><Text className="meta-value">{submitTime(item.createdAt)}</Text></View>
                </View>
              </View>
              <StatusSide value={statusLabel(item.status)} />
            </View>
          ))}
        </View>
      )}
    </Page>
  )
}
