import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { getShopEvaluation, likeShopEvaluation } from '@/api/shop/shopEvaluation'
import type { ShopEvaluation } from '@/api/shop/shopEvaluation/model'

definePageConfig({
  navigationBarTitleText: '评价详情',
})

const EvaluateDetailPage: React.FC = () => {
  const { id } = Taro.getCurrentInstance().router?.params || {}
  const [evaluation, setEvaluation] = useState<ShopEvaluation | null>(null)
  const [loading, setLoading] = useState(true)

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

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

  // 渲染星星
  const renderStars = (score: number) => {
    const stars = []
    for (let i = 1; i <= 5; i++) {
      stars.push(
        <Text key={i} className={i <= score ? 'text-orange-400' : 'text-gray-300'}>★</Text>
      )
    }
    return stars
  }

  // 处理点赞
  const handleLike = async () => {
    if (!evaluation) return
    try {
      await likeShopEvaluation({ evaluationId: evaluation.id, isLiked: !evaluation.isLiked })
      setEvaluation(prev => prev ? {
        ...prev,
        isLiked: !prev.isLiked,
        likes: prev.isLiked ? prev.likes - 1 : prev.likes + 1,
      } : prev)
    } catch (err: any) {
      Taro.showToast({ title: err.message || '操作失败', icon: 'none' })
    }
  }

  // 图片预览
  const handleImagePreview = (index: number) => {
    if (!evaluation?.images?.length) return
    Taro.previewImage({
      current: evaluation.images[index],
      urls: evaluation.images,
    })
  }

  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 (!evaluation) {
    return (
      <View className='min-h-screen bg-gray-50 flex items-center justify-center'>
        <Text className='text-sm text-gray-400'>评价不存在</Text>
      </View>
    )
  }

  return (
    <View className='bg-gray-50 flex flex-col' style={{ minHeight: '100vh' }}>
      <ScrollView scrollY className='flex-1'>
        {/* 用户信息 */}
        <View className='bg-white p-4 mb-3'>
          <View className='flex items-center gap-2 mb-3'>
            <View className='w-10 h-10 rounded-full flex items-center justify-center overflow-hidden' style={{ background: 'linear-gradient(to right, #60a5fa, #c084fc)' }}>
              {evaluation.userAvatar ? (
                <Image src={evaluation.userAvatar} className='w-10 h-10' mode='aspectFill' />
              ) : (
                <Text className='text-white font-bold'>{evaluation.isAnonymous ? '匿' : evaluation.userName[0]}</Text>
              )}
            </View>
            <View className='flex-1'>
              <Text className='text-sm text-gray-700 font-medium block'>{evaluation.userName}</Text>
              <View className='flex items-center gap-1'>{renderStars(evaluation.score)}</View>
            </View>
            <Text className='text-xs text-gray-400'>{evaluation.createTime.split(' ')[0]}</Text>
          </View>
        </View>

        {/* 商品信息 */}
        <View
          className='bg-white p-4 mb-3'
          onClick={() => Taro.navigateTo({ url: `/pages/shop/product-detail?id=${evaluation.goodsId}` })}
        >
          <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 overflow-hidden'>
              {evaluation.goodsImage ? (
                <Image src={evaluation.goodsImage} className='w-12 h-12' mode='aspectFill' />
              ) : (
                <Text className='text-2xl'>🛍️</Text>
              )}
            </View>
            <View className='flex-1'>
              <Text className='text-sm text-gray-700 block'>{evaluation.goodsName}</Text>
              <Text className='text-xs text-gray-400 mt-1 block'>查看商品详情</Text>
            </View>
            <Text className='text-gray-400'>→</Text>
          </View>
        </View>

        {/* 评价内容 */}
        <View className='bg-white p-4 mb-3'>
          <Text className='text-sm text-gray-700 leading-7 block whitespace-pre-wrap'>
            {evaluation.content}
          </Text>

          {/* 评价图片 */}
          {evaluation.images && evaluation.images.length > 0 && (
            <View className='flex flex-wrap gap-2 mt-3'>
              {evaluation.images.map((img, index) => (
                <View
                  key={index}
                  className='w-24 h-24 bg-gray-100 rounded-lg overflow-hidden'
                  onClick={() => handleImagePreview(index)}
                >
                  <Image src={img} className='w-24 h-24' mode='aspectFill' />
                </View>
              ))}
            </View>
          )}
        </View>

        {/* 商家回复 */}
        {evaluation.reply && (
          <View className='bg-white p-4 mb-3'>
            <Text className='text-sm font-medium text-gray-800 mb-2 block'>商家回复</Text>
            <View className='bg-orange-50 rounded-lg p-3'>
              <View className='flex items-center gap-2 mb-2'>
                <View className='bg-orange-500 px-2 py-1 rounded'>
                  <Text className='text-xs text-white'>官方</Text>
                </View>
                {evaluation.replyTime && (
                  <Text className='text-xs text-gray-400'>{evaluation.replyTime}</Text>
                )}
              </View>
              <Text className='text-sm text-gray-700 leading-6'>{evaluation.reply}</Text>
            </View>
          </View>
        )}
      </ScrollView>

      {/* 底部操作栏 */}
      <View className='bg-white border-t border-gray-100 px-4 py-2 flex items-center justify-around' style={{ paddingBottom: '20px' }}>
        <View className='flex flex-col items-center' onClick={handleLike}>
          <Text className={`text-2xl ${evaluation.isLiked ? 'text-red-500' : 'text-gray-400'}`}>
            {evaluation.isLiked ? '❤️' : '🤍'}
          </Text>
          <Text className={`text-xs ${evaluation.isLiked ? 'text-red-500' : 'text-gray-400'}`}>
            {evaluation.likes}
          </Text>
        </View>

        <View
          className='bg-orange-500 text-white px-6 py-2 rounded-full'
          onClick={() => Taro.navigateTo({ url: `/pages/shop/product-detail?id=${evaluation.goodsId}` })}
        >
          <Text className='text-sm text-white'>查看商品</Text>
        </View>
      </View>
    </View>
  )
}

export default EvaluateDetailPage
