import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { listShopPointsOrder, cancelShopPointsOrder } from '@/api/shop/shopPointsOrder'
import type { ShopPointsOrder, PointsOrderStatus } from '@/api/shop/shopPointsOrder'
import EmptyState from '@/components/common/EmptyState'
import LoadMore from '@/components/common/LoadMore'

definePageConfig({
  navigationBarTitleText: '积分订单',
})

// Tab 配置
const TAB_LIST = [
  { title: '全部', status: undefined },
  { title: '待发货', status: 'paid' as PointsOrderStatus },
  { title: '已完成', status: 'completed' as PointsOrderStatus },
  { title: '已取消', status: 'cancelled' as PointsOrderStatus },
]

const PointsOrderListPage: React.FC = () => {
  const [tabIndex, setTabIndex] = useState(0)
  const [orders, setOrders] = useState<ShopPointsOrder[]>([])
  const [loading, setLoading] = useState(false)
  const [finished, setFinished] = useState(false)
  const [page, setPage] = useState(1)

  useEffect(() => {
    setOrders([])
    setPage(1)
    setFinished(false)
    loadList(1)
  }, [tabIndex])

  const loadList = async (p: number) => {
    if (loading) return
    setLoading(true)

    try {
      const status = TAB_LIST[tabIndex]?.status
      const params: any = {
        page: p,
        limit: 10,
      }
      if (status) {
        params.status = status
      }

      const res = await listShopPointsOrder(params)

      if (res?.list) {
        if (p === 1) {
          setOrders(res.list)
        } else {
          setOrders(prev => [...prev, ...res.list])
        }
        setFinished(res.list.length < 10)
        setPage(p)
      }
    } catch (err) {
      console.error('加载积分订单失败', err)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  const handleLoadMore = () => {
    if (!finished && !loading) {
      loadList(page + 1)
    }
  }

  // 取消订单
  const handleCancel = async (id: string) => {
    Taro.showModal({
      title: '确认取消',
      content: '确定取消该订单吗？',
      confirmColor: '#0e932e',
      success: async (res) => {
        if (res.confirm) {
          try {
            await cancelShopPointsOrder(id)
            Taro.showToast({ title: '已取消', icon: 'success' })
            // 重新加载列表
            setOrders([])
            setPage(1)
            setFinished(false)
            loadList(1)
          } catch (err) {
            console.error('取消订单失败', err)
            Taro.showToast({ title: '取消失败', icon: 'none' })
          }
        }
      }
    })
  }

  // 查看详情
  const handleDetail = (id: string) => {
    Taro.navigateTo({ url: `/pages/points/order-detail/index?id=${id}` })
  }

  // 获取状态文本和颜色
  const getStatusInfo = (status: PointsOrderStatus) => {
    const map: Record<PointsOrderStatus, { label: string; color: string }> = {
      'pending': { label: '待支付', color: 'text-orange-500' },
      'paid': { label: '待发货', color: 'text-blue-500' },
      'shipped': { label: '已发货', color: 'text-blue-500' },
      'completed': { label: '已完成', color: 'text-green-500' },
      'cancelled': { label: '已取消', color: 'text-gray-400' },
    }
    return map[status] || { label: '未知', color: 'text-gray-400' }
  }

  return (
    <View className='min-h-screen bg-gray-50 flex flex-col'>
      {/* Tab 栏 */}
      <View className='bg-white flex'>
        {TAB_LIST.map((tab, index) => (
          <View
            key={index}
            className={`flex-1 text-center py-3 relative ${
              tabIndex === index ? 'text-orange-500 font-medium' : 'text-gray-600'
            }`}
            onClick={() => setTabIndex(index)}
          >
            <Text className='text-sm'>{tab.title}</Text>
            {tabIndex === index && (
              <View className='absolute bottom-0 w-8 h-px bg-orange-500 rounded' style={{ left: '50%', transform: 'translateX(-50%)' }} />
            )}
          </View>
        ))}
      </View>

      {/* 订单列表 */}
      <ScrollView
        scrollY
        className='flex-1'
        onScrollToLower={handleLoadMore}
        lowerThreshold={100}
      >
        <View className='p-3'>
          {orders.length > 0 ? (
            orders.map(order => {
              const statusInfo = getStatusInfo(order.status)
              return (
                <View
                  key={order.id}
                  className='bg-white rounded-xl p-4 mb-3'
                  onClick={() => handleDetail(order.id)}
                >
                  {/* 顶部状态 */}
                  <View className='flex justify-between items-center mb-3'>
                    <Text className='text-xs text-gray-500'>{order.orderNo}</Text>
                    <Text className={`text-sm font-medium ${statusInfo.color}`}>
                      {statusInfo.label}
                    </Text>
                  </View>

                  {/* 商品列表 */}
                  {order.items.map((item, idx) => (
                    <View key={idx} className='flex items-center gap-2 mb-2'>
                      <View className='w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center flex-shrink-0'>
                        <Image
                          src={item.goodsImage}
                          className='w-10 h-10 rounded'
                          mode='aspectFill'
                        />
                      </View>
                      <View className='flex-1'>
                        <Text className='text-sm text-gray-800 font-medium block'>{item.goodsName}</Text>
                        <Text className='text-xs text-gray-500 mt-0 block'>
                          {item.points}积分 x {item.quantity}
                        </Text>
                      </View>
                    </View>
                  ))}

                  {/* 底部操作 */}
                  <View className='flex justify-between items-center pt-2 border-t border-gray-50'>
                    <Text className='text-xs text-gray-400'>
                      共 {order.totalPoints} 积分
                    </Text>
                    <View className='flex gap-2'>
                      {order.status === 'paid' && (
                        <View
                          className='text-center py-1 px-3 rounded-full border border-red-500'
                          onClick={(e) => {
                            e.stopPropagation()
                            handleCancel(order.id)
                          }}
                        >
                          <Text className='text-xs text-red-500'>取消订单</Text>
                        </View>
                      )}
                      <View
                        className='text-center py-1 px-3 rounded-full bg-orange-500'
                        onClick={(e) => {
                          e.stopPropagation()
                          handleDetail(order.id)
                        }}
                      >
                        <Text className='text-xs text-white'>查看详情</Text>
                      </View>
                    </View>
                  </View>
                </View>
              )
            })
          ) : !loading ? (
            <EmptyState text='暂无积分订单' />
          ) : null}

          <LoadMore loading={loading} finished={finished} />
        </View>
      </ScrollView>
    </View>
  )
}

export default PointsOrderListPage
