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

export default function ConsultingIndexPage() {
  const [site, setSite] = useState<ConsultingSite | null>(null)
  const [loading, setLoading] = useState(true)

  useDidShow(() => {
    const user = ensureLoggedIn('/pages/consulting/index')
    if (!user) return
    setLoading(true)
    backend.siteConsulting()
      .then(setSite)
      .catch((error) => toast(error instanceof Error ? error.message : '规划咨询加载失败'))
      .finally(() => setLoading(false))
  })

  const directions = site?.directions || []
  const cases = site?.cases || []
  const steps = site?.steps || []
  const firstDirectionUrl = directions[0]?.slug
    ? `/pages/consulting/detail/index?slug=${encodeURIComponent(directions[0].slug)}`
    : '/pages/consulting/apply/index'

  return (
    <Page title={site?.content.heroTitle || '规划咨询'} subtle="提交需求后可在我的咨询查看进度">
      <View className="panel">
        <ProductImage src={site?.content.heroImageUrl || 'consulting'} />
        <View className="panel-pad">
          <Text className="row-title">{site?.content.heroTitle || '规划咨询'}</Text>
          <Text className="row-sub">{site?.content.heroDescription || '正在从后台加载规划咨询内容。'}</Text>
          {site?.content.heroExplanation ? <Text className="row-sub">{site.content.heroExplanation}</Text> : null}
          <View className="primary-btn" style={{ marginTop: '20px' }} onClick={() => go(firstDirectionUrl)}>先看方向介绍</View>
        </View>
      </View>

      <Section title={site?.content.directionTitle || '服务方向'}>
        {directions.length === 0 && !loading ? <EmptyState title="暂无服务方向" text="后台配置规划咨询方向后会显示在这里。" /> : (
          <View className="product-grid">
            {directions.map((item) => (
              <View key={item.id} className="product-card" onClick={() => go(`/pages/consulting/detail/index?slug=${encodeURIComponent(item.slug)}`)}>
                <ProductImage src={item.imageUrl || 'consulting'} />
                <View className="product-body">
                  <Text className="row-title">{item.title}</Text>
                  <Text className="product-desc">{item.summary}</Text>
                  <Text className="price">查看详情</Text>
                </View>
              </View>
            ))}
          </View>
        )}
      </Section>

      {cases.length > 0 && (
        <Section title={site?.content.casesTitle || '过往案例'}>
          {cases.map((item) => (
            <View key={item.id} className="list-line">
              <View style={{ flex: 1 }}>
                <Text className="row-title">{item.title}</Text>
                <Text className="row-sub">{item.type} · {item.summary}</Text>
              </View>
            </View>
          ))}
        </Section>
      )}

      {steps.length > 0 && (
        <Section title={site?.content.stepsTitle || '交付流程'}>
          {steps.map((item, index) => (
            <View key={item.id} className="list-line">
              <Text className="price">{String(index + 1).padStart(2, '0')}</Text>
              <View style={{ flex: 1 }}>
                <Text className="row-title">{item.title}</Text>
                <Text className="row-sub">{item.description}</Text>
              </View>
            </View>
          ))}
        </Section>
      )}
    </Page>
  )
}
