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

export default function ConsultingDirectionDetailPage() {
  const [direction, setDirection] = useState<ConsultingDirection | null>(null)

  useLoad((query) => {
    const user = ensureLoggedIn(`/pages/consulting/detail/index?slug=${encodeURIComponent(String(query.slug || ''))}`)
    if (!user) return
    const slug = String(query.slug || '')
    backend.siteConsulting()
      .then((site) => setDirection(site.directions.find((item) => item.slug === slug) || null))
      .catch((error) => toast(error instanceof Error ? error.message : '方向详情加载失败'))
  })

  if (!direction) {
    return (
      <Page title="规划咨询" subtle="服务方向">
        <EmptyState title="方向不存在" text="该方向可能已隐藏或删除。" />
      </Page>
    )
  }

  return (
    <Page title={direction.title} subtle="规划咨询服务方向">
      <View className="panel">
        <ProductImage src={direction.imageUrl || 'consulting'} />
        <View className="panel-pad">
          <Text className="row-title">{direction.title}</Text>
          <Text className="row-sub">{direction.description || direction.summary}</Text>
          {direction.note ? <Text className="row-sub">{direction.note}</Text> : null}
          {direction.scenarios.length > 0 && (
            <View className="tabs" style={{ marginTop: '24px' }}>
              {direction.scenarios.map((item) => <Text key={item} className="tab">{item}</Text>)}
            </View>
          )}
        </View>
      </View>
      <View className="detail-spacer" />
      <View className="bottom-bar">
        <View className="primary-btn" onClick={() => go(`/pages/consulting/apply/index?direction=${encodeURIComponent(direction.slug)}`)}>提交咨询需求</View>
      </View>
    </Page>
  )
}
