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

export default function StaffTaskDetailPage() {
  const [id, setId] = useState('')
  const [item, setItem] = useState<BackendTask | null>(null)
  const [progressNote, setProgressNote] = useState('')
  const [resultSummary, setResultSummary] = useState('')

  async function loadTask(nextId = id) {
    const token = ensureStaffLoggedIn('/pages/staff/tasks/index')
    if (!token) {
      return
    }
    if (!nextId) return
    try {
      const result = await backend.staffTask(token, nextId)
      setItem(result)
      setProgressNote(result.progressNote || '')
      setResultSummary(result.resultSummary || '')
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '订单详情加载失败', icon: 'none' })
    }
  }

  async function updateTask(payload: Record<string, unknown>, message: string) {
    const token = ensureStaffLoggedIn('/pages/staff/tasks/index')
    if (!token || !item) return
    try {
      const result = await backend.updateStaffTask(token, item.id, payload)
      setItem(result)
      setProgressNote(result.progressNote || '')
      setResultSummary(result.resultSummary || '')
      Taro.showToast({ title: message, icon: 'success' })
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '操作失败', icon: 'none' })
    }
  }

  useLoad((query) => {
    const nextId = String(query.id || '')
    setId(nextId)
    void loadTask(nextId)
  })

  const material = item?.materialPayload || {}

  return (
    <Page title="智能体订单详情" subtle={taskStatusLabel(item?.status)}>
      <View className="staff-detail-card">
        <MetaRow label="订单号" value={item?.orderNo || item?.orderId || '-'} />
        <MetaRow label="智能体" value={item?.productTitle || item?.title || '-'} />
        <MetaRow label="用户手机号" value={item?.userPhone || '-'} />
        <MetaRow label="当前状态" value={taskStatusLabel(item?.status)} />
        <MetaRow label="购买时间" value={formatDateTime(item?.createdAt)} />
        <MetaRow label="更新时间" value={formatDateTime(item?.updatedAt)} />
      </View>

      <View className="staff-detail-card">
        <Text className="staff-section-title">用户提交资料</Text>
        <MetaRow label="联系信息" value={material.contact || '-'} />
        <View className="staff-text-block">
          <Text className="staff-text-label">业务场景 / 配置要求</Text>
          <Text className="staff-text-value">{material.background || item?.progressNote || '暂无资料'}</Text>
        </View>
      </View>

      <View className="staff-detail-card">
        <Text className="staff-section-title">进度更新</Text>
        <Textarea className="form-textarea staff-textarea" value={progressNote} onInput={(event) => setProgressNote(String(event.detail.value))} placeholder="写给用户看的进度说明" />
        <Textarea className="form-textarea staff-textarea" value={resultSummary} onInput={(event) => setResultSummary(String(event.detail.value))} placeholder="交付结果或验收说明" />
      </View>

      <View className="staff-actions">
        {item?.status === 'pending_material' && <View className="staff-action muted">等待用户提交资料</View>}
        {item?.status === 'assigned' && !item.assigneeName && (
          <View className="staff-action" onClick={() => updateTask({ accept: true, progressNote: progressNote || '业务员已接单' }, '已接单')}>接单</View>
        )}
        {item?.status === 'assigned' && (
          <View className="staff-action" onClick={() => updateTask({ status: 'in_progress', progressNote: progressNote || '已开始智能体配置' }, '已开始处理')}>开始处理</View>
        )}
        {item?.status === 'in_progress' && (
          <>
            <View className="staff-action" onClick={() => updateTask({ status: 'in_progress', progressNote }, '进度已更新')}>更新进度</View>
            <View className="staff-action" onClick={() => updateTask({ status: 'pending_confirm', progressNote, resultSummary: resultSummary || '已提交用户确认' }, '已提交确认')}>提交确认</View>
          </>
        )}
        {item?.status === 'pending_confirm' && (
          <View className="staff-action" onClick={() => updateTask({ status: 'completed', progressNote, resultSummary: resultSummary || '已完成交付' }, '已完成交付')}>完成交付</View>
        )}
      </View>
    </Page>
  )
}
