import { ScrollView, Text, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useMemo, useState } from 'react'
import { backend, type BackendOrder, yuan } from '@/api/backend'
import { EmptyState, Page, StatusSide } from '@/components/ui'
import { ensureLoggedIn, getToken, payBackendOrder } from '@/stores/storage'
import type { ProductType } from '@/types'

type OrderTab = 'all' | 'pending' | ProductType

const tabs: Array<{ value: OrderTab; label: string }> = [
  { value: 'all', label: '全部' },
  { value: 'pending', label: '待支付' },
  { value: 'course', label: '课程' },
  { value: 'event', label: '活动' },
  { value: 'data', label: '数据' },
  { value: 'agent', label: '智能体' },
  { value: 'expert', label: '专家' },
  { value: 'consulting', label: '咨询' },
  { value: 'membership', label: '会员' },
]

function orderStatus(order: BackendOrder) {
  if (order.status === 'pending_payment') return '待支付'
  if (order.status === 'closed') return '已关闭'
  return '已支付'
}

function orderTitle(order: BackendOrder) {
  if (order.items.length === 1) return order.items[0].titleSnapshot
  return `${order.items[0]?.titleSnapshot || '订单'}等 ${order.items.length} 项`
}

function orderMeta(order: BackendOrder) {
  const date = new Date(order.createdAt)
  const time = Number.isNaN(date.getTime()) ? '' : date.toLocaleString('zh-CN')
  return `${order.orderNo} · ${time || '时间待同步'}`
}

function matchTab(order: BackendOrder, tab: OrderTab) {
  if (tab === 'all') return true
  if (tab === 'pending') return order.status === 'pending_payment'
  return order.items.some((item) => item.productType === tab)
}

export default function OrdersPage() {
  const [orders, setOrders] = useState<BackendOrder[]>([])
  const [tab, setTab] = useState<OrderTab>('all')
  const [loading, setLoading] = useState(false)
  const [payingOrder, setPayingOrder] = useState('')

  async function loadOrders() {
    const user = ensureLoggedIn('/pages/account/orders/index')
    const token = getToken()
    if (!user || !token) return
    setLoading(true)
    try {
      const result = await backend.accountOrders(token)
      setOrders(result.items)
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '订单加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  useDidShow(() => {
    void loadOrders()
  })

  async function continuePay(order: BackendOrder, event?: { stopPropagation?: () => void }) {
    event?.stopPropagation?.()
    if (payingOrder) return
    setPayingOrder(order.orderNo)
    try {
      await payBackendOrder(order.orderNo)
      Taro.showToast({ title: '支付完成', icon: 'success' })
      await loadOrders()
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '支付失败', icon: 'none' })
    } finally {
      setPayingOrder('')
    }
  }

  const visibleOrders = useMemo(() => orders.filter((order) => matchTab(order, tab)), [orders, tab])

  return (
    <Page title="我的订单" subtle={loading ? '正在同步订单' : `当前 ${visibleOrders.length} 条`}>
      <ScrollView scrollX className="account-tab-scroll" showScrollbar={false}>
        {tabs.map((item) => (
          <View key={item.value} className={tab === item.value ? 'account-filter active' : 'account-filter'} onClick={() => setTab(item.value)}>
            <Text>{item.label}</Text>
          </View>
        ))}
      </ScrollView>

      {orders.length === 0 && !loading ? <EmptyState title="暂无订单" text="购买课程、活动、数据服务或智能体后，会在这里生成订单。" /> : null}
      {orders.length > 0 && !visibleOrders.length ? <EmptyState title="当前分类暂无订单" text="切换其他分类看看，或继续浏览服务。" compact /> : null}

      {!!visibleOrders.length && (
        <View className="list-shell">
          {visibleOrders.map((order) => (
            <View key={order.id || order.orderNo} className="list-line order-line" onClick={() => Taro.navigateTo({ url: `/pages/account/orders/detail/index?id=${encodeURIComponent(order.orderNo)}` })}>
              <View className="list-main">
                <Text className="row-title">{orderTitle(order)}</Text>
                <Text className="row-sub">{orderMeta(order)}</Text>
                <View className="meta-grid">
                  <View><Text className="meta-label">商品小计</Text><Text className="meta-value">¥{yuan(order.subtotalAmount).toLocaleString()}</Text></View>
                  <View><Text className="meta-label">会员优惠</Text><Text className="meta-value">¥{yuan(order.memberDiscountAmount || 0).toLocaleString()}</Text></View>
                  <View><Text className="meta-label">实付金额</Text><Text className="meta-value">¥{yuan(order.totalAmount).toLocaleString()}</Text></View>
                  <View><Text className="meta-label">发票</Text><Text className="meta-value">{order.invoiceApplication ? '已申请' : order.invoiceStatus || '未申请'}</Text></View>
                </View>
                {order.status === 'pending_payment' && (
                  <View className="inline-action" onClick={(event) => void continuePay(order, event)}>
                    {payingOrder === order.orderNo ? '支付中...' : '继续支付'}
                  </View>
                )}
              </View>
              <StatusSide value={orderStatus(order)} orange={order.status === 'pending_payment'} />
            </View>
          ))}
        </View>
      )}
    </Page>
  )
}
