import { ScrollView, Text, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import { backend, mapDataProduct, type BackendConsultingOptionSet } from '@/api/backend'
import { EmptyState, Page, ProductImage, Section } from '@/components/ui'
import { ensureLoggedIn } from '@/stores/storage'
import { toast } from '@/utils/nav'
import type { ServiceProduct } from '@/types'

function optionLabels(optionSets: BackendConsultingOptionSet[], code: string) {
  return (optionSets.find((set) => set.code === code)?.options || [])
    .filter((option) => option.status !== 'disabled')
    .sort((a, b) => a.sortOrder - b.sortOrder)
    .map((option) => option.label)
    .filter(Boolean)
}

export default function DataServicePage() {
  const [products, setProducts] = useState<ServiceProduct[]>([])
  const [optionSets, setOptionSets] = useState<BackendConsultingOptionSet[]>([])
  const [loading, setLoading] = useState(false)

  useDidShow(() => {
    const user = ensureLoggedIn('/pages/data-service/index')
    if (!user) return
    setLoading(true)
    Promise.all([
      backend.dataCatalog(),
      backend.dataServiceOptions()
    ])
      .then(([catalog, options]) => {
        setProducts(catalog.items.map(mapDataProduct))
        setOptionSets(options.optionSets || [])
      })
      .catch((error) => toast(error instanceof Error ? error.message : '数据服务加载失败'))
      .finally(() => setLoading(false))
  })

  const serviceTypes = optionLabels(optionSets, 'data_service_service_type')
  const firstProductUrl = products[0]?.id
    ? `/pages/data-service/detail/index?id=${encodeURIComponent(products[0].id)}`
    : '/pages/data-service/apply/index'

  return (
    <Page title="数据服务" subtle="提交数据主题、地区范围、口径和交付格式，业务员沟通后报价交付">
      <View className="data-service-hero-panel">
        <View className="data-service-hero-copy">
          <Text className="data-service-kicker">申请制服务</Text>
          <Text className="data-service-title">先提交需求，再确认范围与报价</Text>
          <Text className="data-service-text">数据服务不是现货下单。你提交主题、范围、用途和期望成果后，工作人员会联系确认数据边界、合规要求和交付方式。</Text>
          <View className="primary-btn data-service-hero-btn" onClick={() => Taro.navigateTo({ url: firstProductUrl })}>先看服务介绍</View>
        </View>
      </View>

      {serviceTypes.length ? (
        <Section title="服务类型">
          <ScrollView scrollX className="flow-chip-scroll" enhanced showScrollbar={false}>
            {serviceTypes.map((item) => <Text key={item} className="flow-chip">{item}</Text>)}
          </ScrollView>
        </Section>
      ) : null}

      <Section title="参考案例">
        {products.length === 0 && !loading ? (
          <EmptyState title="暂无数据服务案例" text="仍可直接提交数据需求，工作人员会按你的场景沟通。" compact />
        ) : (
          <View className="service-list">
            {products.map((item) => (
              <View key={item.id} className="service-product-row" onClick={() => Taro.navigateTo({ url: `/pages/data-service/detail/index?id=${encodeURIComponent(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">案例参考 · 最终范围以需求沟通为准</Text>
                </View>
                <View className="service-product-side">
                  <Text className="service-product-price">查看</Text>
                </View>
              </View>
            ))}
          </View>
        )}
      </Section>
    </Page>
  )
}
