import React, { useState, useEffect } from 'react'
import { View, Text, Input, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Button } from '@nutui/nutui-react-taro'
import { applyAfterSale } from '@/api/shop/shopAfterSale'
import Price from '@/components/common/Price'

definePageConfig({
  navigationBarTitleText: '申请退款',
})

const REASON_OPTIONS = ['不想要了', '商品描述不符', '商品质量问题', '发货太慢', '其他原因']

const RefundPage: React.FC = () => {
  const { id } = Taro.getCurrentInstance().router?.params || {}
  const [reason, setReason] = useState('')
  const [description, setDescription] = useState('')
  const [selectedReason, setSelectedReason] = useState('')
  const [loading, setLoading] = useState(false)

  const handleSubmit = async () => {
    if (!selectedReason) {
      Taro.showToast({ title: '请选择退款原因', icon: 'none' })
      return
    }

    Taro.showModal({
      title: '确认',
      content: '确定要提交退款申请吗？',
      success: async (res) => {
        if (res.confirm) {
          setLoading(true)
          try {
            Taro.showToast({ title: '提交中...', icon: 'loading' })
            const result = await applyAfterSale({
              orderId: id || '',
              type: 'refund',
              reason: selectedReason,
              description: description,
              amount: 0 // 金额由后端计算
            })
            
            if (result.success) {
              Taro.showToast({ title: '申请已提交', icon: 'success' })
              setTimeout(() => Taro.navigateBack(), 1500)
            } else {
              Taro.showToast({ title: result.message || '提交失败', icon: 'none' })
            }
          } catch (err) {
            console.error('申请退款失败:', err)
            Taro.showToast({ title: '提交失败', icon: 'none' })
          } finally {
            setLoading(false)
          }
        }
      },
    })
  }

  return (
    <View className='min-h-screen bg-gray-50 pb-20 flex flex-col'>
      <ScrollView scrollY className='flex-1'>
        {/* 退款原因 */}
        <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-wrap gap-2'>
            {REASON_OPTIONS.map(r => (
              <View
                key={r}
                className={`px-3 py-1 rounded-full text-sm ${
                  selectedReason === r
                    ? 'bg-green-50 text-green-600 border border-green-500'
                    : 'bg-gray-50 text-gray-600 border border-gray-200'
                }`}
                onClick={() => setSelectedReason(r)}
              >
                <Text>{r}</Text>
              </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-2 block'>退款说明</Text>
          <View className='w-full bg-gray-50 rounded-lg p-3 text-sm'>
            <Input
              className='w-full'
              placeholder='选填，请详细描述退款原因'
              value={description}
              onInput={e => setDescription(e.detail.value)}
              style={{ minHeight: '120px' }}
            />
          </View>
        </View>
      </ScrollView>

      {/* 提交按钮 */}
      <View className='bg-white border-t border-gray-100 p-3' style={{ paddingBottom: '20px' }}>
        <Button
          type='primary'
          className='w-full rounded-full'
          style={{ backgroundColor: '#ee0a24' }}
          onClick={handleSubmit}
        >
          提交申请
        </Button>
      </View>
    </View>
  )
}

export default RefundPage
