import { Text, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import { backend, yuan, type BackendDataServiceRequest } from '@/api/backend'
import { Page } from '@/components/ui'
import { ensureStaffLoggedIn } from '@/stores/storage'
import { dataServiceStatusLabel, formatDateTime } from '../shared'

const scopes = [
  { label: '待接单', value: 'pool' },
  { label: '我负责', value: 'mine' },
  { label: '已完成', value: 'completed' },
]

const filters = [
  { label: '全部', value: '' },
  { label: '等待联系', value: 'pending_contact' },
  { label: '沟通中', value: 'contacting' },
  { label: '待付款', value: 'quoted' },
  { label: '服务中', value: 'in_service' },
  { label: '已完成', value: 'completed' },
]

export default function StaffDataServicesPage() {
  const [items, setItems] = useState<BackendDataServiceRequest[]>([])
  const [scope, setScope] = useState('pool')
  const [status, setStatus] = useState('')

  async function loadRequests(nextStatus = status, nextScope = scope) {
    const token = ensureStaffLoggedIn('/pages/staff/data-services/index')
    if (!token) {
      return
    }
    try {
      const result = await backend.staffDataServiceRequests(token, {
        status: nextScope === 'completed' ? 'completed' : nextStatus,
        scope: nextScope === 'completed' ? 'mine' : nextScope,
      })
      setItems(result.items)
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '数据服务单加载失败', icon: 'none' })
    }
  }

  useDidShow(() => { void loadRequests(status, scope) })

  return (
    <Page title="数据服务单" subtle={`当前 ${items.length} 个`}>
      <View className="staff-filter">
        {scopes.map((item) => (
          <View
            key={item.value}
            className={scope === item.value ? 'staff-filter-chip active' : 'staff-filter-chip'}
            onClick={() => {
              setScope(item.value)
              void loadRequests(status, item.value)
            }}
          >
            {item.label}
          </View>
        ))}
      </View>
      <View className="staff-filter">
        {filters.map((item) => (
          <View
            key={item.value || 'all'}
            className={status === item.value ? 'staff-filter-chip active' : 'staff-filter-chip'}
            onClick={() => {
              setStatus(item.value)
              void loadRequests(item.value, scope)
            }}
          >
            {item.label}
          </View>
        ))}
      </View>

      <View className="staff-list">
        {items.map((item) => (
          <View key={item.id} className="staff-list-line" onClick={() => Taro.navigateTo({ url: `/pages/staff/data-services/detail?id=${encodeURIComponent(item.id)}` })}>
            <View className="staff-list-main">
              <Text className="staff-list-title">{item.dataTopic || item.quotedTitle || '数据服务申请'}</Text>
              <Text className="staff-list-sub">{item.company} · {item.contactName} · {item.contactPhone || item.userPhone || '-'}</Text>
              <Text className="staff-list-meta">
                {item.quotedAmount ? `¥${yuan(item.quotedAmount).toLocaleString()} · ` : ''}
                更新 {formatDateTime(item.updatedAt)}
              </Text>
            </View>
            <Text className="staff-list-status">{dataServiceStatusLabel(item.status)}</Text>
          </View>
        ))}
        {!items.length && <View className="staff-empty">暂无数据服务单</View>}
      </View>
    </Page>
  )
}
