import React, { useState, useEffect } from 'react'
import { View, Text, Image, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Button } from '@nutui/nutui-react-taro'
import { getAfterSaleDetail, cancelAfterSale, formatAfterSaleStatus, AFTER_SALE_TYPE_MAP } from '@/api/shop/shopAfterSale'
import type { AfterSaleDetail } from '@/api/shop/shopAfterSale'
import Price from '@/components/common/Price'

definePageConfig({
  navigationBarTitleText: '售后详情',
})

const AfterSaleDetailPage: React.FC = () => {
  const { id, orderId } = Taro.getCurrentInstance().router?.params || {}
  const [detail, setDetail] = useState<AfterSaleDetail | null>(null)
  const [loading, setLoading] = useState(false)
  const [cancelling, setCancelling] = useState(false)

  useEffect(() => {
    loadDetail()
  }, [id, orderId])

  const loadDetail = async () => {
    setLoading(true)
    try {
      const res = await getAfterSaleDetail({ afterSaleId: id, orderId })
      if (res?.data) {
        setDetail(res.data)
      }
    } catch (err) {
      console.error('加载售后详情失败', err)
    } finally {
      setLoading(false)
    }
  }

  // 取消申请
  const handleCancel = () => {
    Taro.showModal({
      title: '确认取消',
      content: '确定要撤销售后申请吗？取消后不可恢复。',
      success: async (res) => {
        if (res.confirm) {
          setCancelling(true)
          try {
            // await cancelAfterSale(id || '')
            await new Promise(resolve => setTimeout(resolve, 1000))
            Taro.showToast({ title: '已取消申请', icon: 'success' })
            setTimeout(() => {
              Taro.navigateBack()
            }, 1500)
          } catch (err) {
            Taro.showToast({ title: '取消失败', icon: 'none' })
          } finally {
            setCancelling(false)
          }
        }
      },
    })
  }

  // 格式化时间
  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')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
  }

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

  const statusInfo = formatAfterSaleStatus(detail.status)
  const canCancel = ['pending'].includes(detail.status)

  return (
    <View className='min-h-screen bg-gray-50 pb-20 flex flex-col'>
      <ScrollView scrollY className='flex-1'>
        {/* 状态头部 */}
        <View
          className='p-5 text-center'
          style={{ backgroundColor: statusInfo.color }}
        >
          <Text className='text-white text-xl font-medium block'>{statusInfo.text}</Text>
          {detail.status === 'processing' && (
            <Text className='text-white text-sm opacity-80 mt-1 block'>
              预计1-3个工作日内处理
            </Text>
          )}
          {detail.status === 'pending' && (
            <Text className='text-white text-sm opacity-80 mt-1 block'>
              等待商家审核中
            </Text>
          )}
          {detail.status === 'approved' && (
            <Text className='text-white text-sm opacity-80 mt-1 block'>
              商家已同意，请按提示操作
            </Text>
          )}
          {detail.status === 'completed' && (
            <Text className='text-white text-sm opacity-80 mt-1 block'>
              退款已原路返回
            </Text>
          )}
          {detail.status === 'rejected' && (
            <Text className='text-white text-sm opacity-80 mt-1 block'>
              {detail.rejectReason || '商家拒绝了您的申请'}
            </Text>
          )}
        </View>

        {/* 进度时间线 */}
        <View className='bg-white mx-3 mt-3 p-4 rounded-xl'>
          <Text className='text-sm font-medium text-gray-800 mb-3 block'>处理进度</Text>
          <View className='relative'>
            {/* 竖线 */}
            <View className='absolute left-4 top-0 bottom-0 w-px bg-gray-200' />

            {detail.progressRecords.map((record, idx) => (
              <View key={record.id} className={`relative flex gap-3 pb-4 ${idx === detail.progressRecords.length - 1 ? 'pb-0' : ''}`}>
                {/* 圆点 */}
                <View
                  className={`w-8 h-8 rounded-full flex items-center justify-center z-10 ${
                    idx === 0 ? 'bg-green-500' : 'bg-gray-200'
                  }`}
                >
                  {idx === 0 ? (
                    <Text className='text-white text-xs'>✓</Text>
                  ) : (
                    <View className='w-2 h-2 rounded-full bg-gray-400' />
                  )}
                </View>

                {/* 内容 */}
                <View className='flex-1 pt-1'>
                  <View className='flex justify-between items-center'>
                    <Text className={`text-sm font-medium ${
                      idx === 0 ? 'text-gray-800' : 'text-gray-500'
                    }`}>
                      {record.status}
                    </Text>
                    <Text className='text-xs text-gray-400'>{formatTime(record.time)}</Text>
                  </View>
                  <Text className={`text-xs mt-1 ${idx === 0 ? 'text-gray-600' : 'text-gray-400'}`}>
                    {record.description}
                  </Text>
                  {record.operator && (
                    <Text className='text-xs text-gray-400 mt-1'>
                      操作人: {record.operator}
                    </Text>
                  )}
                </View>
              </View>
            ))}
          </View>
        </View>

        {/* 售后信息 */}
        <View className='bg-white mx-3 mt-3 p-4 rounded-xl'>
          <Text className='text-sm font-medium text-gray-800 mb-3 block'>售后信息</Text>
          <View className="flex flex-col" style={{ gap: '8px' }}>
            <View className='flex justify-between'>
              <Text className='text-sm text-gray-500'>售后类型</Text>
              <Text className='text-sm text-gray-800'>
                {AFTER_SALE_TYPE_MAP[detail.type] || detail.type}
              </Text>
            </View>
            <View className='flex justify-between'>
              <Text className='text-sm text-gray-500'>申请原因</Text>
              <Text className='text-sm text-gray-800'>{detail.reason}</Text>
            </View>
            {detail.description && (
              <View className='flex justify-between'>
                <Text className='text-sm text-gray-500'>补充说明</Text>
                <Text className='text-sm text-gray-800 max-w-50 text-right'>{detail.description}</Text>
              </View>
            )}
            <View className='flex justify-between'>
              <Text className='text-sm text-gray-500'>申请时间</Text>
              <Text className='text-sm text-gray-800'>{formatTime(detail.applyTime)}</Text>
            </View>
            {detail.contactPhone && (
              <View className='flex justify-between'>
                <Text className='text-sm text-gray-500'>联系电话</Text>
                <Text className='text-sm text-gray-800'>{detail.contactPhone}</Text>
              </View>
            )}
          </View>
        </View>

        {/* 退款金额 */}
        <View className='bg-white mx-3 mt-3 p-4 rounded-xl'>
          <View className='flex justify-between items-center'>
            <Text className='text-sm font-medium text-gray-800'>退款金额</Text>
            <Text className='text-xl font-bold text-red-500'>
              {'\u00A5'}{detail.amount.toFixed(2)}
            </Text>
          </View>
          <Text className='text-xs text-gray-400 mt-2 block'>
            退款将原路返回，微信支付退款一般1-3个工作日到账
          </Text>
        </View>

        {/* 凭证图片 */}
        {detail.evidenceImages && detail.evidenceImages.length > 0 && (
          <View className='bg-white mx-3 mt-3 p-4 rounded-xl'>
            <Text className='text-sm font-medium text-gray-800 mb-3 block'>凭证图片</Text>
            <View className='flex gap-2 flex-wrap'>
              {detail.evidenceImages.map((url, idx) => (
                <Image
                  key={idx}
                  className='w-20 h-20 rounded-lg'
                  src={url}
                  mode='aspectFill'
                />
              ))}
            </View>
          </View>
        )}

        {/* 订单信息 */}
        <View className='bg-white mx-3 mt-3 p-4 rounded-xl mb-4'>
          <View className='flex justify-between items-center mb-2'>
            <Text className='text-sm font-medium text-gray-800'>关联订单</Text>
            <View
              className='px-3 py-1 rounded-full bg-gray-50'
              onClick={() => Taro.navigateTo({ url: `/pages/order/detail?id=${detail.orderId}` })}
            >
              <Text className='text-xs text-gray-500'>查看订单 ›</Text>
            </View>
          </View>
          <Text className='text-sm text-gray-400'>订单号: {detail.orderNo}</Text>
        </View>
      </ScrollView>

      {/* 底部按钮 */}
      {canCancel && (
        <View className='bg-white border-t border-gray-100 p-3' style={{ paddingBottom: '20px' }}>
          <Button
            type='default'
            className='w-full rounded-full border-gray-200'
            loading={cancelling}
            onClick={handleCancel}
          >
            撤销售后申请
          </Button>
        </View>
      )}
    </View>
  )
}

export default AfterSaleDetailPage
