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

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

const filters = [
  { label: '全部', value: '' },
  { label: '待接单', value: 'pending' },
  { label: '已接单', value: 'assigned' },
  { label: '沟通中', value: 'communicating' },
  { label: '方案中', value: 'planning' },
  { label: '待确认报价', value: 'proposal_ready' },
  { label: '待支付', value: 'pending_payment' },
  { label: '服务中', value: 'in_service' },
  { label: '已完成', value: 'completed' },
]

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

  async function loadRequests(nextStatus = status, nextScope = scope) {
    const token = ensureStaffLoggedIn('/pages/staff/consulting/index')
    if (!token) {
      return
    }
    try {
      const result = await backend.staffConsultingRequests(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/consulting/detail?id=${encodeURIComponent(item.id)}` })}>
            <View className="staff-list-main">
              <Text className="staff-list-title">{item.direction}</Text>
              <Text className="staff-list-sub">{item.company} · {item.contactName}</Text>
              <Text className="staff-list-meta">{item.urgency || '未设紧急度'} · 更新 {formatDateTime(item.updatedAt)}</Text>
            </View>
            <Text className="staff-list-status">{consultingStatusLabel(item.status)}</Text>
          </View>
        ))}
        {!items.length && <View className="staff-empty">暂无咨询服务单</View>}
      </View>
    </Page>
  )
}
