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

definePageConfig({
  navigationBarTitleText: '售后进度',
})

const AfterSaleProgressPage: React.FC = () => {
  const { id } = Taro.getCurrentInstance().router?.params || {}
  const [saleInfo, setSaleInfo] = useState<AfterSaleDetail | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (id) {
      fetchDetail(id)
    }
  }, [id])

  const fetchDetail = async (saleId: string) => {
    try {
      const data = await getAfterSaleDetail(saleId)
      setSaleInfo(data)
    } catch (err: any) {
      Taro.showToast({ title: err.message || '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  // 取消售后
  const handleCancel = () => {
    if (!saleInfo) return
    Taro.showModal({
      title: '提示',
      content: '确定取消售后申请吗？',
      confirmColor: '#0e932e',
      success: async (res) => {
        if (res.confirm) {
          try {
            await cancelAfterSale(saleInfo.id)
            Taro.showToast({ title: '已取消', icon: 'success' })
            fetchDetail(saleInfo.id)
          } catch (err: any) {
            Taro.showToast({ title: err.message || '取消失败', icon: 'none' })
          }
        }
      }
    })
  }

  if (loading) {
    return (
      <View className='min-h-screen bg-gray-50 flex items-center justify-center'>
        <Text className='text-sm text-gray-400'>加载中...</Text>
      </View>
    )
  }

  if (!saleInfo) {
    return (
      <View className='min-h-screen bg-gray-50 flex items-center justify-center'>
        <Text className='text-sm text-gray-400'>暂无数据</Text>
      </View>
    )
  }

  const statusInfo = formatAfterSaleStatus(saleInfo.status)

  // 售后类型名称
  const getTypeLabel = (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'>
        {/* 状态卡片 */}
        <View className='p-4 text-white' style={{ background: 'linear-gradient(to right, #60a5fa, #22d3ee)' }}>
          <Text className='text-2xl font-bold block mb-2'>{statusInfo.text}</Text>
          <Text className='text-sm opacity-80 block mb-1'>售后编号：{saleInfo.id}</Text>
          <Text className='text-sm opacity-80 block'>申请时间：{saleInfo.applyTime}</Text>
        </View>

        {/* 售后信息 */}
        <View className='bg-white mx-3 rounded-xl p-4 relative z-10 shadow-sm' style={{ marginTop: '-12px' }}>
          <Text className='text-sm font-medium text-gray-800 mb-3 block'>售后信息</Text>

          <View className='flex justify-between py-2 border-b border-gray-50'>
            <Text className='text-sm text-gray-500'>售后类型</Text>
            <Text className='text-sm text-gray-800'>{getTypeLabel(saleInfo.type)}</Text>
          </View>
          <View className='flex justify-between py-2 border-b border-gray-50'>
            <Text className='text-sm text-gray-500'>售后原因</Text>
            <Text className='text-sm text-gray-800'>{saleInfo.reason}</Text>
          </View>
          {saleInfo.type === 'refund' && (
            <View className='flex justify-between py-2 border-b border-gray-50'>
              <Text className='text-sm text-gray-500'>退款金额</Text>
              <Text className='text-sm text-red-500 font-bold'>¥{saleInfo.amount}</Text>
            </View>
          )}
          {saleInfo.rejectReason && (
            <View className='flex justify-between py-2 border-b border-gray-50'>
              <Text className='text-sm text-gray-500'>拒绝原因</Text>
              <Text className='text-sm text-red-500 flex-1 text-right'>{saleInfo.rejectReason}</Text>
            </View>
          )}
          <View className='flex justify-between py-2'>
            <Text className='text-sm text-gray-500'>关联订单</Text>
            <View className='flex items-center gap-1' onClick={() => Taro.navigateTo({ url: `/pages/order/detail?id=${saleInfo.orderId}` })}>
              <Text className='text-sm text-blue-500'>{saleInfo.orderNo || saleInfo.orderId}</Text>
              <Text className='text-gray-400 text-xs'>→</Text>
            </View>
          </View>
        </View>

        {/* 进度步骤 */}
        {saleInfo.progressRecords && saleInfo.progressRecords.length > 0 && (
          <View className='bg-white mx-3 mt-3 rounded-xl p-4'>
            <Text className='text-sm font-medium text-gray-800 mb-3 block'>处理进度</Text>
            {saleInfo.progressRecords.map((record, index) => (
              <View key={record.id} className={`flex mb-3 ${index === saleInfo.progressRecords.length - 1 ? 'mb-0' : ''}`}>
                <View className='flex flex-col items-center mr-3'>
                  <View className='w-3 h-3 rounded-full mt-1 bg-green-500' />
                  {index < saleInfo.progressRecords.length - 1 && (
                    <View className='w-px flex-1 bg-green-500' />
                  )}
                </View>
                <View className='flex-1 pb-3'>
                  <Text className='text-sm font-medium text-gray-800 block'>{record.status}</Text>
                  <Text className='text-xs text-gray-500 mt-0 block'>{record.description}</Text>
                  {record.remark && <Text className='text-xs text-gray-400 mt-1 block'>{record.remark}</Text>}
                  <Text className='text-xs text-gray-400 mt-1 block'>{record.time}</Text>
                </View>
              </View>
            ))}
          </View>
        )}

        {/* 商品信息 */}
        {saleInfo.goodsName && (
          <View className='bg-white mx-3 mt-3 rounded-xl p-4'>
            <Text className='text-sm font-medium text-gray-800 mb-3 block'>商品信息</Text>
            <View className='flex items-center gap-2'>
              <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>
              <Text className='text-sm text-gray-700 flex-1'>{saleInfo.goodsName}</Text>
            </View>
          </View>
        )}

        {/* 操作按钮 */}
        {saleInfo.status === 'pending' && (
          <View className='p-3'>
            <View
              className='text-center py-3 rounded-full border border-red-500'
              onClick={handleCancel}
            >
              <Text className='text-sm text-red-500'>取消申请</Text>
            </View>
          </View>
        )}

        <View className='h-6' />
      </ScrollView>
    </View>
  )
}

export default AfterSaleProgressPage
