import { Text, View } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { EmptyState, MetaRow, Page, ProductImage } from '@/components/ui'
import { backend, type BackendDataProduct } from '@/api/backend'
import { ensureLoggedIn } from '@/stores/storage'
import { toast } from '@/utils/nav'

function formatFileSize(value?: number) {
  const size = Number(value || 0)
  if (!size) return '沟通后确认'
  if (size >= 1024 * 1024) return `${Math.round(size / 1024 / 1024)} MB`
  if (size >= 1024) return `${Math.round(size / 1024)} KB`
  return `${size} B`
}

function compactText(value?: string | null) {
  return String(value || '').trim()
}

export default function DataServiceDetailPage() {
  const [product, setProduct] = useState<BackendDataProduct | null>(null)
  const [loading, setLoading] = useState(true)

  useLoad((query) => {
    const id = String(query.id || query.slug || '')
    const user = ensureLoggedIn(`/pages/data-service/detail/index?id=${encodeURIComponent(id)}`)
    if (!user) return
    setLoading(true)
    backend.dataProduct(id)
      .then(setProduct)
      .catch((error) => toast(error instanceof Error ? error.message : '数据服务详情加载失败'))
      .finally(() => setLoading(false))
  })

  if (!product && !loading) {
    return (
      <Page title="数据服务" subtle="服务介绍">
        <EmptyState title="服务不存在" text="该数据服务可能已下架或隐藏。" />
      </Page>
    )
  }

  const tags = (product?.tags || []).filter(Boolean)
  const introBlocks = [
    { title: '适用目标', text: compactText(product?.caseGoal || product?.summary) },
    { title: '需求口径', text: compactText(product?.requestOutline) },
    { title: '交付说明', text: compactText(product?.deliveryOutline || product?.serviceNote) }
  ].filter((item) => item.text)

  return (
    <Page title={product?.title || '数据服务'} subtle="先了解服务范围，再提交找数需求">
      <View className="panel">
        <ProductImage src={product?.coverUrl || 'data'} />
        <View className="panel-pad">
          <Text className="row-title">{product?.title || '正在加载数据服务'}</Text>
          <Text className="row-sub">{product?.summary || '正在从真实后端加载服务介绍。'}</Text>
          {tags.length > 0 ? (
            <View className="tabs" style={{ marginTop: '24px' }}>
              {tags.map((item) => <Text key={item} className="tab">{item}</Text>)}
            </View>
          ) : null}
        </View>
      </View>

      <View className="flow-section">
        <Text className="flow-section-title">服务信息</Text>
        <MetaRow label="服务类型" value={product?.category || '数据服务'} />
        <MetaRow label="交付格式" value={product?.fileFormat || '沟通后确认'} />
        <MetaRow label="参考大小" value={formatFileSize(product?.fileSize)} />
      </View>

      {introBlocks.map((item) => (
        <View key={item.title} className="flow-section">
          <Text className="flow-section-title">{item.title}</Text>
          <Text className="row-sub">{item.text}</Text>
        </View>
      ))}

      <View className="detail-spacer" />
      <View className="bottom-bar">
        <View className="primary-btn" onClick={() => Taro.navigateTo({ url: `/pages/data-service/apply/index?productId=${encodeURIComponent(product?.id || '')}` })}>按这个方向找数据</View>
      </View>
    </Page>
  )
}
