import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Tabs } from '@nutui/nutui-react-taro'
import { pageAfterSaleList } from '@/api/shop/shopAfterSale'
import type { AfterSaleDetail, AfterSaleStatus } from '@/api/shop/shopAfterSale'
import { formatAfterSaleStatus, AFTER_SALE_STATUS_MAP } from '@/api/shop/shopAfterSale'
import EmptyState from '@/components/common/EmptyState'
import LoadMore from '@/components/common/LoadMore'

definePageConfig({
  navigationBarTitleText: '售后列表',
})

// Tab 配置
const TAB_LIST = [
  { title: '全部', status: undefined },
  { title: '处理中', status: 'processing' as AfterSaleStatus },
  { title: '待收货', status: 'approved' as AfterSaleStatus },
  { title: '已完成', status: 'completed' as AfterSaleStatus },
  { title: '已拒绝', status: 'rejected' as AfterSaleStatus },
]

// 状态对应的 API 查询值
const STATUS_QUERY_MAP: Record<string, AfterSaleStatus | undefined> = {
  'processing': 'processing',
  'approved': 'approved',
  'completed': 'completed',
  'rejected': 'rejected',
}

const AfterSaleListPage: React.FC = () => {
  const [tabIndex, setTabIndex] = useState(0)
  const [list, setList] = useState<AfterSaleDetail[]>([])
  const [loading, setLoading] = useState(false)
  const [finished, setFinished] = useState(false)
  const [page, setPage] = useState(1)

  useEffect(() => {
    setList([])
    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 res = await pageAfterSaleList({
        page: p,
        pageSize: 10,
        status: STATUS_QUERY_MAP[status || ''],
      })

      const newList = res?.data?.list || []
      if (p === 1) {
        setList(newList)
      } else {
        setList(prev => [...prev, ...newList])
      }
      setFinished(newList.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 goToDetail = (item: AfterSaleDetail) => {
    Taro.navigateTo({
      url: `/pages/order/after-sale-detail?id=${item.id}&orderId=${item.orderId}`,
    })
  }

  // 格式化时间
  const formatTime = (time: string) => {
    if (!time) return ''
    const date = new Date(time)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }

  // 售后类型文字
  const getTypeText = (type: string) => {
    const map: Record<string, string> = {
      refund: '退款',
      return: '退货退款',
      exchange: '换货',
      repair: '维修',
    }
    return map[type] || type
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      <Tabs value={tabIndex} onChange={(val) => setTabIndex(val as number)} type='smile'>
        {TAB_LIST.map((tab) => (
          <Tabs.TabPane key={tab.title} title={tab.title}>
            <ScrollView
              scrollY
              className='flex-1'
              onScrollToLower={handleLoadMore}
              lowerThreshold={100}
            >
              <View className='p-3'>
                {list.length > 0 ? (
                  list.map(item => {
                    const statusInfo = formatAfterSaleStatus(item.status)
                    return (
                      <View
                        key={item.id}
                        className='bg-white rounded-xl p-4 mb-3'
                        onClick={() => goToDetail(item)}
                      >
                        {/* 状态头部 */}
                        <View className='flex justify-between items-center mb-3'>
                          <Text className='text-sm text-gray-400'>订单号: {item.orderNo}</Text>
                          <View className='flex items-center gap-1'>
                            <Text className='text-sm font-medium' style={{ color: statusInfo.color }}>
                              {statusInfo.text}
                            </Text>
                            <Text className='text-gray-400'>›</Text>
                          </View>
                        </View>

                        {/* 售后类型 */}
                        <View className='flex items-center gap-2 mb-2'>
                          <View className={`px-2 py-1 rounded text-xs ${
                            item.type === 'refund' ? 'bg-blue-50 text-blue-600' : 'bg-orange-50 text-orange-600'
                          }`}>
                            <Text>{getTypeText(item.type)}</Text>
                          </View>
                          <Text className='text-sm text-gray-600'>{item.reason}</Text>
                        </View>

                        {/* 金额 */}
                        <View className='flex justify-between items-center pt-2 border-t border-gray-50'>
                          <Text className='text-xs text-gray-400'>申请时间: {formatTime(item.applyTime)}</Text>
                          <View className='flex items-center gap-1'>
                            <Text className='text-xs text-gray-500'>退款金额</Text>
                            <Text className='text-base font-bold text-red-500'>
                              {'\u00A5'}{item.amount.toFixed(2)}
                            </Text>
                          </View>
                        </View>
                      </View>
                    )
                  })
                ) : !loading ? (
                  <EmptyState text='暂无售后记录' />
                ) : null}

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

export default AfterSaleListPage
