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

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

const filters = [
  { label: '全部', value: '' },
  { label: '待资料', value: 'pending_material' },
  { label: '待接单', value: 'assigned' },
  { label: '配置中', value: 'in_progress' },
  { label: '待确认', value: 'pending_confirm' },
  { label: '已完成', value: 'completed' },
]

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

  async function loadTasks(nextStatus = status, nextScope = scope) {
    const token = ensureStaffLoggedIn('/pages/staff/tasks/index')
    if (!token) {
      return
    }
    try {
      const result = await backend.staffTasks(token, {
        type: 'agent',
        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 loadTasks(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 loadTasks(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 loadTasks(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/tasks/detail?id=${encodeURIComponent(item.id)}` })}>
            <View className="staff-list-main">
              <Text className="staff-list-title">{item.productTitle || item.title}</Text>
              <Text className="staff-list-sub">{taskSummary(item)}</Text>
              <Text className="staff-list-meta">用户 {item.userPhone || '-'} · 更新 {formatDateTime(item.updatedAt)}</Text>
            </View>
            <Text className="staff-list-status">{taskStatusLabel(item.status)}</Text>
          </View>
        ))}
        {!items.length && <View className="staff-empty">暂无智能体订单</View>}
      </View>
    </Page>
  )
}
