import React, { useState, useEffect, useCallback, useRef } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { pageShopOrder } from '@/api/shop/shopOrder'
import type { ShopOrder, ShopOrderParam } from '@/api/shop/shopOrder/model'
import { OrderListStatus, OrderListTabText } from '@/types/order'
import OrderCard from '@/components/common/OrderCard'
import EmptyState from '@/components/common/EmptyState'
import LoadMore from '@/components/common/LoadMore'

definePageConfig({
  navigationBarTitleText: '我的订单',
})

// Tab 配置（使用后端 statusFilter 字段）
const tabList = [
  { title: OrderListTabText[OrderListStatus.All], status: OrderListStatus.All },
  { title: OrderListTabText[OrderListStatus.Unpaid], status: OrderListStatus.Unpaid },
  { title: OrderListTabText[OrderListStatus.Unshipped], status: OrderListStatus.Unshipped },
  { title: OrderListTabText[OrderListStatus.Shipped], status: OrderListStatus.Shipped },
  { title: OrderListTabText[OrderListStatus.Completed], status: OrderListStatus.Completed },
]

interface TabState {
  orders: ShopOrder[]
  page: number
  finished: boolean
  loading: boolean
  initialized: boolean
}

const OrderListPage: React.FC = () => {
  const initTab = Taro.getCurrentInstance().router?.params?.tab
    ?? Taro.getStorageSync('order_tab')
  // 读取后清除，避免影响下次进入
  if (Taro.getStorageSync('order_tab') !== '') {
    Taro.removeStorageSync('order_tab')
  }
  const [tabIndex, setTabIndex] = useState(Number(initTab) || 0)

  // 每个 tab 独立维护状态
  const [tabStates, setTabStates] = useState<TabState[]>(
    tabList.map(() => ({
      orders: [],
      page: 1,
      finished: false,
      loading: false,
      initialized: false,
    }))
  )

  const currentState = tabStates[tabIndex]

  // 用 ref 避免 loadOrders 闭包中捕获过期状态
  const tabStatesRef = useRef(tabStates)
  tabStatesRef.current = tabStates

  const updateTabState = useCallback(
    (index: number, partial: Partial<TabState>) => {
      setTabStates(prev => {
        const next = [...prev]
        next[index] = { ...next[index], ...partial }
        return next
      })
    },
    []
  )

  const loadOrders = useCallback(
    async (targetIndex: number, p: number) => {
      const state = tabStatesRef.current[targetIndex]
      if (state.loading) return

      updateTabState(targetIndex, { loading: true })

      try {
        const params: ShopOrderParam = { page: p, limit: 10 }
        const status = tabList[targetIndex]?.status

        // 使用后端 statusFilter 字段进行筛选
        // -1=全部, 0=待支付, 1=待发货, 3=待收货, 5=已完成
        if (status !== undefined && status !== OrderListStatus.All) {
          params.statusFilter = status
        }

        const res = await pageShopOrder(params)
        const list = res?.list || []

        updateTabState(targetIndex, {
          orders: p === 1 ? list : [...state.orders, ...list],
          page: p,
          finished: list.length < 10,
          loading: false,
          initialized: true,
        })
      } catch {
        updateTabState(targetIndex, { loading: false, initialized: true })
      }
    },
    [updateTabState]
  )

  // 切换 tab 时加载数据
  useEffect(() => {
    if (!tabStates[tabIndex].initialized) {
      loadOrders(tabIndex, 1)
    }
  }, [tabIndex])

  const handleLoadMore = () => {
    if (!currentState.finished && !currentState.loading) {
      loadOrders(tabIndex, currentState.page + 1)
    }
  }

  const handleTabChange = (index: number) => {
    if (index !== tabIndex) {
      setTabIndex(index)
    }
  }

  return (
    <View className='min-h-screen bg-gray-50 flex flex-col'>
      {/* 自定义 Tabs 标题栏 */}
      <View className='bg-white flex flex-row items-center border-b border-gray-100'>
        {tabList.map((tab, index) => (
          <View
            key={tab.title}
            className='flex-1 flex flex-col items-center justify-center py-3'
            onClick={() => handleTabChange(index)}
          >
            <Text
              className='text-sm font-medium'
              style={{
                color: index === tabIndex ? '#ee0a24' : '#666',
              }}
            >
              {tab.title}
            </Text>
            {index === tabIndex && (
              <View
                className='mt-1 rounded-full'
                style={{
                  width: '20px',
                  height: '3px',
                  backgroundColor: '#ee0a24',
                }}
              />
            )}
          </View>
        ))}
      </View>

      {/* 内容区域 - 每个 tab 独立渲染 */}
      <View className='flex-1 relative'>
        {tabList.map((tab, idx) => (
          <View
            key={tab.title}
            className='absolute inset-0'
            style={{
              display: idx === tabIndex ? 'flex' : 'none',
              flexDirection: 'column',
            }}
          >
            <ScrollView
              scrollY
              className='flex-1'
              onScrollToLower={handleLoadMore}
              lowerThreshold={100}
            >
              <View className='p-3'>
                {tabStates[idx].orders.length > 0 ? (
                  tabStates[idx].orders.map(order => (
                    <OrderCard key={order.orderId} order={order} />
                  ))
                ) : tabStates[idx].initialized && !tabStates[idx].loading ? (
                  <EmptyState text='暂无订单' />
                ) : null}
                <LoadMore
                  loading={tabStates[idx].loading}
                  finished={tabStates[idx].finished}
                />
              </View>
            </ScrollView>
          </View>
        ))}
      </View>
    </View>
  )
}

export default OrderListPage
