import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView, Image, Input } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Button } from '@nutui/nutui-react-taro'
import { useUser } from '@/hooks/useUser'
import { submitGoodsComment } from '@/api/shop/shopGoodsComment'

definePageConfig({
  navigationBarTitleText: '商品评价',
})

const EvaluatePage: React.FC = () => {
  const { isLoggedIn } = useUser()
  const { orderId, orderGoodsId, goodsId } = Taro.getCurrentInstance().router?.params || {}

  const [rating, setRating] = useState(5)
  const [content, setContent] = useState('')
  const [images, setImages] = useState<string[]>([])
  const [isAnonymous, setIsAnonymous] = useState(false)

  useEffect(() => {
    if (!isLoggedIn) {
      Taro.navigateTo({ url: '/passport/login' })
    }
  }, [isLoggedIn])

  const handleSubmit = async () => {
    if (!content.trim()) {
      Taro.showToast({ title: '请输入评价内容', icon: 'none' })
      return
    }

    if (!orderId || !orderGoodsId || !goodsId) {
      Taro.showToast({ title: '参数错误', icon: 'none' })
      return
    }

    Taro.showModal({
      title: '提交评价',
      content: '确定要提交评价吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const submitRes = await submitGoodsComment({
              oid: Number(orderId),
              goodsId: Number(goodsId),
              goodsScore: rating,
              serviceScore: rating,
              comment: content,
              pics: images.join(','),
            })

            if (submitRes.code === 0) {
              Taro.showToast({ title: '评价成功', icon: 'success' })
              setTimeout(() => Taro.navigateBack(), 1500)
            } else {
              Taro.showToast({ title: submitRes.message || '提交失败', icon: 'none' })
            }
          } catch (err: any) {
            Taro.showToast({ title: err.message || '提交失败', icon: 'none' })
          }
        }
      },
    })
  }

  const handleChooseImage = () => {
    Taro.chooseImage({
      count: 9 - images.length,
      success: (res) => {
        setImages([...images, ...res.tempFilePaths])
      },
    })
  }

  const handleRemoveImage = (index: number) => {
    const newImages = [...images]
    newImages.splice(index, 1)
    setImages(newImages)
  }

  if (!isLoggedIn) {
    return null
  }

  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-lg'>
          <Text className='text-sm font-medium text-gray-800 mb-3 block'>商品评分</Text>
          <View className='flex gap-2'>
            {[1, 2, 3, 4, 5].map((star) => (
              <View
                key={star}
                onClick={() => setRating(star)}
              >
                <Text className='text-2xl'>
                  {star <= rating ? '⭐' : '☆'}
                </Text>
              </View>
            ))}
          </View>
        </View>

        {/* 评价内容 */}
        <View className='bg-white mx-3 mt-3 p-4 rounded-lg'>
          <Text className='text-sm font-medium text-gray-800 mb-2 block'>评价内容</Text>
          <View className='bg-gray-50 rounded-lg p-3'>
            <Input
              value={content}
              onInput={(e) => setContent(e.detail.value)}
              placeholder='请输入评价内容'
              className='w-full text-sm'
              style={{ minHeight: '120px' }}
            />
          </View>
        </View>

        {/* 上传图片 */}
        <View className='bg-white mx-3 mt-3 p-4 rounded-lg'>
          <Text className='text-sm font-medium text-gray-800 mb-2 block'>上传图片</Text>
          <View className='flex flex-wrap gap-2'>
            {images.map((img, idx) => (
              <View key={idx} className='relative'>
                <Image
                  src={img}
                  className='w-20 h-20 rounded-lg'
                  mode='aspectFill'
                />
                <View
                  className='absolute top-0 right-0 w-5 h-5 bg-red-500 rounded-full flex items-center justify-center'
                  onClick={() => handleRemoveImage(idx)}
                >
                  <Text className='text-white text-xs'>×</Text>
                </View>
              </View>
            ))}
            {images.length < 9 && (
              <View
                className='w-20 h-20 bg-gray-100 rounded-lg flex items-center justify-center'
                onClick={handleChooseImage}
              >
                <Text className='text-2xl text-gray-400'>+</Text>
              </View>
            )}
          </View>
        </View>

        {/* 匿名评价 */}
        <View
          className='bg-white mx-3 mt-3 p-4 rounded-lg flex items-center justify-between'
          onClick={() => setIsAnonymous(!isAnonymous)}
        >
          <Text className='text-sm text-gray-700'>匿名评价</Text>
          <View
            className={`w-12 h-6 rounded-full relative ${
              isAnonymous ? 'bg-green-500' : 'bg-gray-300'
            }`}
          >
            <View
              className={`absolute top-1 w-4 h-4 bg-white rounded-full ${
                isAnonymous ? 'right-1' : 'left-1'
              }`}
            />
          </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: '#0e932e' }}
          onClick={handleSubmit}
        >
          提交评价
        </Button>
      </View>
    </View>
  )
}

export default EvaluatePage
