import { ScrollView, Text, View } from '@tarojs/components'
import { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import type { ProductType } from '@/types'
import { EmptyState, Page, ProductImage, SearchPill } from '@/components/ui'
import { backend, mapAgentProduct, mapCourseProduct, mapDataProduct, mapEventProduct, mapExpertProduct } from '@/api/backend'
import { consultingProduct, serviceCategories } from '@/constants/services'
import { toProduct, toast } from '@/utils/nav'
import type { ServiceProduct } from '@/types'

function servicePrice(item: ServiceProduct) {
  if (item.price === 0) return item.status || '提交需求'
  return `¥${item.price.toLocaleString()}`
}

export default function ServiceListPage() {
  const [type, setType] = useState<ProductType>('course')
  const [products, setProducts] = useState<ServiceProduct[]>([])
  useLoad((query) => {
    const nextType = (query.type as ProductType) || 'course'
    setType(nextType)
    loadProducts(nextType)
      .catch((error) => toast(error instanceof Error ? error.message : '服务数据加载失败'))
  })

  async function loadProducts(nextType: ProductType) {
    if (nextType === 'consulting') {
      setProducts([consultingProduct])
      return
    }
    if (nextType === 'expert') {
      const result = await backend.experts({ available: true })
      setProducts(result.items.map(mapExpertProduct))
      return
    }
    if (nextType === 'course') {
      const result = await backend.courseCatalog()
      setProducts(result.items.map(mapCourseProduct))
      return
    }
    if (nextType === 'event') {
      const result = await backend.eventCatalog()
      setProducts(result.items.map(mapEventProduct))
      return
    }
    if (nextType === 'data') {
      const result = await backend.dataCatalog()
      setProducts(result.items.map(mapDataProduct))
      return
    }
    if (nextType === 'agent') {
      const result = await backend.agentCatalog()
      setProducts(result.items.map(mapAgentProduct))
    }
  }

  const title = serviceCategories.find((item) => item.key === type)?.label || '服务'
  const items = products.filter((item) => item.type === type)

  return (
    <Page title={title}>
      <SearchPill text={`搜索${title}`} placeholder={`请输入${title}关键词`} />
      <ScrollView scrollX className="category-scroll">
        {serviceCategories.map((item) => (
          <Text key={item.key} className={item.key === type ? 'category-chip active' : 'category-chip'} onClick={() => { setType(item.key); void loadProducts(item.key) }}>
            {item.label}
          </Text>
        ))}
      </ScrollView>

      {items.length === 0 ? (
        <EmptyState title={type === 'expert' ? '暂无可预约专家' : `暂无${title}`} text={type === 'expert' ? '请前往 Web 端专家平台选择专家并提交预约。' : undefined} />
      ) : (
        <View className="service-list">
          {items.map((item) => (
            <View key={item.id} className="service-product-row" onClick={() => toProduct(item.id)}>
              <ProductImage className="service-product-thumb" src={item.cover} />
              <View className="service-product-main">
                <Text className="service-product-title">{item.title}</Text>
                <Text className="service-product-summary">{item.summary || item.subtitle}</Text>
                <Text className="service-product-meta">{item.subtitle}</Text>
              </View>
              <View className="service-product-side">
                <Text className="service-product-price">{servicePrice(item)}</Text>
                <Text className="service-product-action">查看</Text>
              </View>
            </View>
          ))}
        </View>
      )}
    </Page>
  )
}
