import { Input, Text, Textarea, View } from '@tarojs/components'
import { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { backend, type BackendAgentProduct } from '@/api/backend'
import { Page, ProductImage } from '@/components/ui'
import { getDeliveryTask, submitBackendTaskMaterials } from '@/stores/storage'
import type { DeliveryTask } from '@/types'
import { tapMedium } from '@/utils/feedback'

export default function AgentDetailPage() {
  const [task, setTask] = useState<DeliveryTask | null>(null)
  const [organization, setOrganization] = useState('')
  const [contact, setContact] = useState('')
  const [background, setBackground] = useState('请补充业务场景、输入材料格式和希望生成的结果。')
  const [submitting, setSubmitting] = useState(false)
  const [product, setProduct] = useState<BackendAgentProduct | null>(null)

  useLoad((query) => {
    const current = getDeliveryTask(query.id || '')
    setTask(current)
    if (current?.productId) {
      backend.agentProduct(current.productId).then(setProduct).catch(() => undefined)
    }
  })

  async function submitMaterials() {
    if (!task) return
    tapMedium()
    setSubmitting(true)
    try {
      const updated = await submitBackendTaskMaterials(task.id, { organization, contact, background })
      setTask(updated)
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Page title={task?.title || '智能体交付'}>
      <View className="panel">
        <ProductImage src={product?.coverUrl || 'agent'} />
        <View className="panel-pad">
          <Text className="row-title">功能说明</Text>
          <Text className="row-sub">{task ? product?.deliveryNote || `订单 ${task.orderNo} · 当前状态：${task.statusText}` : '未找到对应交付任务，请返回刷新。'}</Text>
          <View className="tabs" style={{ marginTop: '24px' }}>
            {(task?.steps || ['提交资料', '需求审核', '智能体配置', '交付验收']).map((item, index) => (
              <Text key={item} className={index === (task?.currentStep || 0) ? 'tab active' : 'tab'}>{item}</Text>
            ))}
          </View>
          <View style={{ height: '24px' }} />
          {task?.status === 'pending_material' && (
            <View className="form-card">
              <Input value={organization} onInput={(event) => setOrganization(String(event.detail.value))} placeholder="使用机构" className="form-input" />
              <Input value={contact} onInput={(event) => setContact(String(event.detail.value))} placeholder="联系手机号" className="form-input" />
              <Textarea value={background} onInput={(event) => setBackground(String(event.detail.value))} className="form-textarea" />
            </View>
          )}
          <View className="primary-btn" onClick={submitMaterials}>{submitting ? '提交中...' : task?.status === 'pending_material' ? '提交材料' : '已提交，查看进度'}</View>
        </View>
      </View>
    </Page>
  )
}
