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

definePageConfig({
  navigationBarTitleText: '售后记录',
})

const AfterSaleListPage: React.FC = () => {
  const [sales, setSales] = useState<AfterSaleDetail[]>([])
  const [loading, setLoading] = useState(false)
  const [finished, setFinished] = useState(false)
  const [page, setPage] = useState(1)

  useEffect(() => {
    loadList(1)
  }, [])

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

    try {
      const res = await pageAfterSaleList({
        page: p,
        pageSize: 10,
      })

      const newList = res?.list || []
      if (p === 1) {
        setSales(newList)
      } else {
        setSales(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 handleDetail = (id: string) => {
    Taro.navigateTo({ url: `/pages/after-sale/progress/index?id=${id}` })
  }

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

  // 售后类型文字
  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 flex flex-col'>
      <ScrollView scrollY className='flex-1' onScrollToLower={handleLoadMore}>
        {sales.length === 0 ? (
          <View className='text-center py-16'>
            <Text className='text-4xl mb-3 block'>📋</Text>
            <Text className='text-sm text-gray-400 mb-3 block'>暂无售后记录</Text>
            <View
              className='inline-block bg-blue-500 text-white px-4 py-2 rounded-full'
              onClick={() => Taro.navigateTo({ url: '/pages/order/list' })}
            >
              <Text className='text-sm'>去申请售后</Text>
            </View>
          </View>
        ) : (
          <View className='p-3'>
            {sales.map(sale => {
              const statusInfo = formatAfterSaleStatus(sale.status)
              return (
                <View key={sale.id} className='bg-white rounded-xl p-4 mb-3 shadow-sm'>
                  {/* 顶部信息 */}
                  <View className='flex justify-between items-center mb-3'>
                    <View className='flex items-center gap-2'>
                      <Text className='text-xs text-gray-500'>{sale.id}</Text>
                      <View className='bg-gray-100 px-2 py-1 rounded'>
                        <Text className='text-xs text-gray-600'>{getTypeText(sale.type)}</Text>
                      </View>
                    </View>
                    <Text className={`text-sm font-medium ${statusInfo.color}`}>
                      {statusInfo.text}
                    </Text>
                  </View>

                  {/* 商品信息 */}
                  <View className='flex items-center gap-2 mb-3'>
                    <View className='w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center flex-shrink-0'>
                      <Text className='text-2xl'>🛍️</Text>
                    </View>
                    <View className='flex-1'>
                      <Text className='text-sm text-gray-700 block'>{sale.goodsName}</Text>
                      {sale.type === 'refund' && (
                        <Text className='text-xs text-red-500 mt-1 block'>退款金额：¥{sale.amount}</Text>
                      )}
                    </View>
                  </View>

                  {/* 时间 */}
                  <Text className='text-xs text-gray-400 mb-3 block'>
                    申请时间：{sale.applyTime}
                  </Text>

                  {/* 操作按钮 */}
                  <View className='flex justify-end gap-2 pt-2 border-t border-gray-50'>
                    {sale.status === 'processing' && (
                      <View
                        className='px-3 py-1 rounded-full border border-red-500'
                        onClick={(e) => {
                          e.stopPropagation()
                          handleCancel(sale.id)
                        }}
                      >
                        <Text className='text-xs text-red-500'>取消申请</Text>
                      </View>
                    )}
                    <View
                      className='px-3 py-1 rounded-full bg-blue-500'
                      onClick={() => handleDetail(sale.id)}
                    >
                      <Text className='text-xs text-white'>查看进度</Text>
                    </View>
                  </View>
                </View>
              )
            })}
          </View>
        )}
        <LoadMore loading={loading} finished={finished} />
        <View className='h-6' />
      </ScrollView>
    </View>
  )
}

export default AfterSaleListPage
