import { ScrollView, Text, View } from '@tarojs/components'
import { useDidShow, useTabItemTap } from '@tarojs/taro'
import { useState } from 'react'
import { EmptyState, Page, ProductImage, SearchPill, Section } from '@/components/ui'
import { backend, mapAgentProduct, mapCourseProduct, mapEventProduct, type BackendExpertProfile } from '@/api/backend'
import { consultingProduct } from '@/constants/services'
import { ensureLoggedIn } from '@/stores/storage'
import type { ProductType, ServiceProduct } from '@/types'
import { toProduct, toServiceList, toast } from '@/utils/nav'
import { tapMedium } from '@/utils/feedback'

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

export default function ServicesPage() {
  const [courses, setCourses] = useState<ServiceProduct[]>([])
  const [events, setEvents] = useState<ServiceProduct[]>([])
  const [agents, setAgents] = useState<ServiceProduct[]>([])
  const [experts, setExperts] = useState<BackendExpertProfile[]>([])
  useTabItemTap(tapMedium)

  useDidShow(() => {
    ensureLoggedIn('/pages/services/index')
    Promise.all([
      backend.courseCatalog(),
      backend.eventCatalog(),
      backend.agentCatalog(),
      backend.siteHome(),
      backend.experts({ available: true })
    ])
      .then(([courseData, eventData, agentData, siteHome, expertData]) => {
        setCourses(courseData.items.map(mapCourseProduct))
        setEvents(eventData.items.map(mapEventProduct))
        setAgents(agentData.items.map(mapAgentProduct))
        setExperts((siteHome.featuredExperts?.length ? siteHome.featuredExperts : expertData.items).slice(0, 8))
      })
      .catch((error) => toast(error instanceof Error ? error.message : '服务数据加载失败'))
  })

  function shelf(title: string, subtitle: string, items: ServiceProduct[], type: ProductType) {
    return (
      <Section title={title} action={<Text className="service-shelf-action" onClick={() => toServiceList(type)}>全部</Text>}>
        {items.length === 0 ? <EmptyState title={`暂无${title}`} compact /> : (
          <ScrollView scrollX className="service-shelf-scroll" enhanced showScrollbar={false}>
            {items.slice(0, 8).map((item) => (
              <View key={item.id} className="service-shelf-card" onClick={() => toProduct(item.id)}>
                <ProductImage className="service-shelf-image" src={item.cover} />
                <Text className="service-shelf-title">{item.title}</Text>
                <Text className="service-shelf-sub">{item.subtitle || subtitle}</Text>
                <Text className="service-shelf-price">{servicePrice(item)}</Text>
              </View>
            ))}
          </ScrollView>
        )}
      </Section>
    )
  }

  function expertShelf() {
    return (
      <Section title="专家预约" action={<Text className="service-shelf-action" onClick={() => toServiceList('expert')}>全部</Text>}>
        {experts.length === 0 ? <EmptyState title="暂无可预约专家" compact /> : (
          <ScrollView scrollX className="service-shelf-scroll" enhanced showScrollbar={false}>
            {experts.map((expert) => (
              <View key={expert.id} className="expert-shelf-card" onClick={() => toProduct(`expert-${expert.slug || expert.id}`)}>
                <ProductImage className="expert-shelf-avatar" src={expert.photoUrl || 'expert'} label={expert.name.slice(0, 1)} />
                <Text className="expert-shelf-name">{expert.name}</Text>
                <Text className="expert-shelf-title">{expert.title || expert.organization}</Text>
                <Text className="expert-shelf-tags">{(expert.directions || expert.specialties || []).slice(0, 2).join(' / ') || '专家咨询'}</Text>
              </View>
            ))}
          </ScrollView>
        )}
      </Section>
    )
  }

  return (
    <Page title="服务" subtle="课程、活动、数据服务、智能体与专家预约">
      <SearchPill text="搜索服务名称或专家" />

      {shelf('课程学习', '线上/线下课程', courses, 'course')}
      {shelf('活动报名', '近期活动', events, 'event')}

      <Section title="规划咨询">
        <View className="consulting-feature-row" onClick={() => toProduct(consultingProduct.id)}>
          <View className="consulting-feature-main">
            <Text className="consulting-feature-kicker">需求评估与方案规划</Text>
            <Text className="consulting-feature-title">{consultingProduct.title}</Text>
            <Text className="consulting-feature-text">{consultingProduct.summary}</Text>
            <Text className="consulting-feature-action">提交咨询需求</Text>
          </View>
        </View>
      </Section>

      {expertShelf()}
      {shelf('智能体服务', '资料提交与交付', agents, 'agent')}

      <Section title="数据服务">
        <View className="consulting-feature-row data-feature-row" onClick={() => toServiceList('data')}>
          <View className="consulting-feature-main">
            <Text className="consulting-feature-kicker">数据产品与定制需求</Text>
            <Text className="consulting-feature-title">数据服务</Text>
            <Text className="consulting-feature-text">查看已发布的数据产品，也可以按主题、地区、行业和格式提交定制数据需求。</Text>
            <Text className="consulting-feature-action">提交数据需求</Text>
          </View>
        </View>
      </Section>
    </Page>
  )
}
