import { Text, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import { EmptyState, Page, ProductImage, Section } from '@/components/ui'
import { backend, type BackendAgentProduct } from '@/api/backend'
import { ensureLoggedIn, getDeliveryTasks, refreshBackendTasks } from '@/stores/storage'
import type { DeliveryTask } from '@/types'

export default function AgentsPage() {
  const [tasks, setTasks] = useState<DeliveryTask[]>([])
  const [agents, setAgents] = useState<BackendAgentProduct[]>([])
  const opened = tasks.filter((item) => item.type === 'agent')
  const openedProductIds = new Set(opened.map((item) => item.productId))
  const locked = agents.filter((item) => !openedProductIds.has(item.id))

  useDidShow(() => {
    const user = ensureLoggedIn('/pages/account/agents/index')
    if (!user) return
    setTasks(getDeliveryTasks())
    Promise.all([
      refreshBackendTasks(),
      backend.agentCatalog()
    ])
      .then(([nextTasks, catalog]) => {
        setTasks(nextTasks)
        setAgents(catalog.items)
      })
      .catch(() => undefined)
  })

  return (
    <Page title="我的智能体">
      <Section title="已开通">
        {opened.length === 0 ? <EmptyState title="暂无已开通智能体" text="购买智能体服务并完成支付后，会在这里显示交付进度。" /> : (
          <View className="agent-list">
            {opened.map((item) => (
              <View key={item.id} className="agent-card" onClick={() => Taro.navigateTo({ url: `/pages/account/agents/detail/index?id=${item.id}` })}>
                <ProductImage className="agent-thumb" src={agents.find((agent) => agent.id === item.productId)?.coverUrl || 'agent'} />
                <View style={{ flex: 1 }}>
                  <View className="agent-title-row">
                    <Text className="row-title">{item.title}</Text>
                    <Text className="agent-status active">{item.statusText}</Text>
                  </View>
                  <Text className="product-desc">订单 {item.orderNo} · 更新 {new Date(item.updatedAt).toLocaleString('zh-CN')}</Text>
                  <View className="agent-progress"><View className="agent-progress-fill" style={{ width: `${Math.max(20, (item.currentStep + 1) * 25)}%` }} /></View>
                </View>
              </View>
            ))}
          </View>
        )}
      </Section>
      <Section title="未开通">
        <View className="agent-list">
          {locked.map((item) => (
            <View key={item.id} className="agent-card muted" onClick={() => Taro.navigateTo({ url: `/pages/services/detail/index?id=${item.id}` })}>
              <ProductImage className="agent-thumb" src={item.coverUrl || 'agent'} />
              <View style={{ flex: 1 }}>
                <View className="agent-title-row">
                  <Text className="row-title">{item.title}</Text>
                  <Text className="agent-status">未开通</Text>
                </View>
                <Text className="product-desc">{item.summary || item.detailDescription}</Text>
              </View>
            </View>
          ))}
        </View>
      </Section>
    </Page>
  )
}
