import React, { useState } from 'react'
import { View, Text, Textarea, ScrollView, Radio, RadioGroup, Checkbox, Input } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { applyAfterSale } from '@/api/shop/shopAfterSale'
import type { AfterSaleType } from '@/api/shop/shopAfterSale'

definePageConfig({
  navigationBarTitleText: '申请售后',
})

const AfterSaleApplyPage: React.FC = () => {
  const params = Taro.getCurrentInstance().router?.params || {}
  const orderId = params.orderId || ''
  const [orderGoods, setOrderGoods] = useState<Array<{ id: number; name: string; price: number; num: number; checked: boolean }>>([])
  const [saleType, setSaleType] = useState(1) // 1:退款, 2:退货退款, 3:换货
  const [submitting, setSubmitting] = useState(false)
  const [reason, setReason] = useState('')
  const [amount, setAmount] = useState('')
  const [description, setDescription] = useState('')
  const [images, setImages] = useState<string[]>([])

  // 退款原因选项
  const refundReasons = ['商品质量问题', '商品与描述不符', '商品破损/缺陷', '物流问题', '其他']
  const returnReasons = ['商品质量问题', '商品与描述不符', '商品破损/缺陷', '尺码/颜色不合适', '不喜欢/不想要', '其他']
  const exchangeReasons = ['商品质量问题', '商品与描述不符', '商品破损/缺陷', '尺码/颜色不合适', '其他']

  // 获取当前原因列表
  const getCurrentReasons = () => {
    if (saleType === 1) return refundReasons
    if (saleType === 2) return returnReasons
    return exchangeReasons
  }

  // 处理商品选择
  const handleGoodsCheck = (id: number) => {
    setOrderGoods(prev =>
      prev.map(g => g.id === id ? { ...g, checked: !g.checked } : g)
    )
  }

  // 选择图片
  const handleChooseImage = () => {
    if (images.length >= 6) {
      Taro.showToast({ title: '最多上传6张图片', icon: 'none' })
      return
    }
    Taro.chooseImage({
      count: 6 - images.length,
      success: (res) => {
        setImages(prev => [...prev, ...res.tempFilePaths])
      }
    })
  }

  // 删除图片
  const handleDeleteImage = (index: number) => {
    setImages(prev => prev.filter((_, i) => i !== index))
  }

  // 提交申请
  const handleSubmit = () => {
    const checkedGoods = orderGoods.filter(g => g.checked)
    if (!reason) {
      Taro.showToast({ title: '请选择原因', icon: 'none' })
      return
    }
    if (saleType === 1 && !amount) {
      Taro.showToast({ title: '请输入退款金额', icon: 'none' })
      return
    }

    const typeMap: Record<number, AfterSaleType> = {
      1: 'refund',
      2: 'return',
      3: 'exchange',
    }

    Taro.showModal({
      title: '确认提交',
      content: '确定提交售后申请吗？',
      confirmColor: '#0e932e',
      success: async (res) => {
        if (res.confirm) {
          setSubmitting(true)
          Taro.showLoading({ title: '提交中...' })
          try {
            await applyAfterSale({
              orderId,
              type: typeMap[saleType],
              reason,
              description,
              amount: saleType === 1 ? Number(amount) : undefined,
              evidenceImages: images,
              goodsItems: checkedGoods.map(g => ({ goodsId: String(g.id), quantity: g.num })),
            })
            Taro.hideLoading()
            Taro.showToast({ title: '提交成功', icon: 'success' })
            setTimeout(() => Taro.navigateBack(), 1500)
          } catch (err: any) {
            Taro.hideLoading()
            Taro.showToast({ title: err.message || '提交失败', icon: 'none' })
          } finally {
            setSubmitting(false)
          }
        }
      }
    })
  }

  return (
    <View className='bg-gray-50 flex flex-col' style={{ minHeight: '100vh' }}>
      <ScrollView scrollY className='flex-1'>
        {/* 订单商品 */}
        <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>
          {orderGoods.map(goods => (
            <View
              key={goods.id}
              className='flex items-center gap-3 py-2 border-b border-gray-50'
              onClick={() => handleGoodsCheck(goods.id)}
            >
              <Checkbox checked={goods.checked} color='#0e932e' />
              <View className='w-12 h-12 bg-gray-100 rounded flex items-center justify-center flex-shrink-0'>
                <Text className='text-xl'>🛍️</Text>
              </View>
              <View className='flex-1'>
                <Text className='text-sm text-gray-700 block'>{goods.name}</Text>
                <Text className='text-xs text-gray-400 mt-1 block'>¥{goods.price} × {goods.num}</Text>
              </View>
            </View>
          ))}
        </View>

        {/* 售后类型 */}
        <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>
          <RadioGroup onChange={(e) => setSaleType(parseInt(e.detail.value))}>
            <View className='flex flex-col gap-2'>
              <View className='flex items-center gap-2'>
                <Radio value='1' checked={saleType === 1} color='#0e932e' />
                <Text className='text-sm text-gray-700'>仅退款</Text>
              </View>
              <View className='flex items-center gap-2'>
                <Radio value='2' checked={saleType === 2} color='#0e932e' />
                <Text className='text-sm text-gray-700'>退货退款</Text>
              </View>
              <View className='flex items-center gap-2'>
                <Radio value='3' checked={saleType === 3} color='#0e932e' />
                <Text className='text-sm text-gray-700'>换货</Text>
              </View>
            </View>
          </RadioGroup>
        </View>

        {/* 退款金额 */}
        {saleType === 1 && (
          <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 bg-gray-50 rounded-lg px-3 py-2'>
              <Text className='text-gray-500 mr-1'>¥</Text>
              <Input
                type='digit'
                value={amount}
                onInput={(e) => setAmount(e.detail.value)}
                placeholder='请输入退款金额'
                className='flex-1'
              />
            </View>
            <Text className='text-xs text-gray-400 mt-2 block'>最多可退 ¥134.00</Text>
          </View>
        )}

        {/* 售后原因 */}
        <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 flex-col gap-2'>
            {getCurrentReasons().map((r, index) => (
              <View
                key={index}
                className={`p-2 rounded-lg border ${
                  reason === r ? 'border-orange-500 bg-orange-50' : 'border-gray-200'
                }`}
                onClick={() => setReason(r)}
              >
                <Text className={`text-sm ${reason === r ? 'text-orange-500' : 'text-gray-700'}`}>
                  {r}
                </Text>
              </View>
            ))}
          </View>
        </View>

        {/* 问题描述 */}
        <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>
          <Textarea
            value={description}
            onInput={(e) => setDescription(e.detail.value)}
            placeholder='请详细描述您的问题（选填）'
            className='w-full min-h-20 p-2 bg-gray-50 rounded-lg text-sm'
            maxlength={500}
          />
          <Text className='text-xs text-gray-400 mt-1 block text-right'>{description.length}/500</Text>
        </View>

        {/* 上传凭证 */}
        <View className='bg-white mx-3 mt-3 rounded-xl p-4 mb-3'>
          <Text className='text-sm font-medium text-gray-800 mb-3 block'>上传凭证（选填）</Text>
          <View className='flex flex-wrap gap-2'>
            {images.map((img, index) => (
              <View key={index} className='relative'>
                <View className='w-16 h-16 bg-gray-100 rounded-lg flex items-center justify-center'>
                  <Text className='text-2xl'>🖼️</Text>
                </View>
                <View
                  className='absolute -top-1 -right-1 w-4 h-4 bg-red-500 rounded-full flex items-center justify-center'
                  onClick={() => handleDeleteImage(index)}
                >
                  <Text className='text-xs text-white'>×</Text>
                </View>
              </View>
            ))}
            {images.length < 6 && (
              <View
                className='w-16 h-16 bg-gray-50 rounded-lg flex items-center justify-center border-2 border-dashed border-gray-300'
                onClick={handleChooseImage}
              >
                <Text className='text-2xl text-gray-400'>+</Text>
              </View>
            )}
          </View>
        </View>

        <View className='h-4' />
      </ScrollView>

      {/* 提交按钮 */}
      <View className='bg-white p-3 shadow-lg' style={{ paddingBottom: '20px' }}>
        <View
          className='text-center py-3 rounded-full text-white font-bold'
          style={{ background: submitting ? '#ccc' : 'linear-gradient(to right, #f97316, #ef4444)' }}
          onClick={submitting ? undefined : handleSubmit}
        >
          <Text className='text-white font-bold'>{submitting ? '提交中...' : '提交申请'}</Text>
        </View>
      </View>
    </View>
  )
}

export default AfterSaleApplyPage
