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

function statusLabel(status: BackendDataServiceRequest['status']) {
  if (status === 'pending_contact') return '等待联系'
  if (status === 'contacting') return '沟通中'
  if (status === 'quoted') return '待付款'
  if (status === 'pending_payment') return '待支付'
  if (status === 'in_service') return '服务进行中'
  if (status === 'completed') return '服务已完成'
  if (status === 'cancelled') return '已取消'
  return '处理中'
}

export default function ReportsPage() {
  const [requests, setRequests] = useState<BackendDataServiceRequest[]>([])
  const [reports, setReports] = useState<BackendDataProduct[]>([])
  const [loading, setLoading] = useState(false)

  useDidShow(() => {
    const user = ensureLoggedIn('/pages/account/reports/index')
    const token = getToken()
    if (!user || !token) return
    setLoading(true)
    Promise.all([
      backend.accountDataServiceRequests(token),
      backend.accountDataProducts(token)
    ])
      .then(([serviceData, reportData]) => {
        setRequests(serviceData.items)
        setReports(reportData.items)
      })
      .catch((error) => Taro.showToast({ title: error instanceof Error ? error.message : '数据服务加载失败', icon: 'none' }))
      .finally(() => setLoading(false))
  })

  const total = requests.length + reports.length

  return (
    <Page title="我的数据服务" subtle={loading ? '正在同步服务进度' : `当前 ${requests.length} 个服务单`}>
      {!total && !loading ? (
        <EmptyState
          title="暂无数据服务"
          text="提交数据需求后，会在这里查看等待联系、报价付款、服务进度和下载入口。"
          action={<View className="ghost-btn" onClick={() => Taro.navigateTo({ url: '/pages/data-service/apply/index' })}>我要找数据</View>}
        />
      ) : (
        <>
          <View className="list-shell">
            {requests.map((item) => (
              <View key={item.id} className="list-line" onClick={() => Taro.navigateTo({ url: `/pages/account/reports/detail/index?id=${encodeURIComponent(item.id)}` })}>
                <View className="list-main">
                  <Text className="row-title">{item.dataTopic || item.quotedTitle || '数据服务申请'}</Text>
                  <Text className="row-sub">{item.company} · {item.serviceType || '数据服务'}</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">{item.quotedAmount ? `¥${yuan(item.quotedAmount).toLocaleString()}` : '待沟通'}</Text></View>
                  </View>
                </View>
                <StatusSide value={statusLabel(item.status)} orange={item.status === 'quoted' || item.status === 'pending_payment'} />
              </View>
            ))}
          </View>

          {!!reports.length && (
            <View style={{ marginTop: '28px' }}>
              <Text className="row-title">历史数据包（只读）</Text>
              <View style={{ height: '16px' }} />
              <View className="report-grid">
                {reports.map((item) => (
                  <View key={item.id} onClick={() => Taro.navigateTo({ url: `/pages/account/reports/detail/index?id=${encodeURIComponent(item.id)}` })}>
                    <ProductImage className="report-cover" src={item.coverUrl || 'data'} />
                    <Text className="row-title">{item.title}</Text>
                  </View>
                ))}
              </View>
            </View>
          )}
        </>
      )}
    </Page>
  )
}
