import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { listShopEvaluation, likeShopEvaluation } from '@/api/shop/shopEvaluation'
import type { ShopEvaluation } from '@/api/shop/shopEvaluation'
import EmptyState from '@/components/common/EmptyState'
import LoadMore from '@/components/common/LoadMore'

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

const EvaluateListPage: React.FC = () => {
  const [evaluations, setEvaluations] = useState<ShopEvaluation[]>([])
  const [sortBy, setSortBy] = useState('newest') // newest, mostLiked
  const [loading, setLoading] = useState(false)
  const [finished, setFinished] = useState(false)
  const [page, setPage] = useState(1)

  useEffect(() => {
    setEvaluations([])
    setPage(1)
    setFinished(false)
    loadList(1)
  }, [sortBy])

  const loadList = async (p: number) => {
    if (loading) return
    setLoading(true)

    try {
      const res = await listShopEvaluation({
        page: p,
        limit: 10,
        sortBy: sortBy as 'newest' | 'mostLiked',
      })

      if (res?.list) {
        if (p === 1) {
          setEvaluations(res.list)
        } else {
          setEvaluations(prev => [...prev, ...res.list])
        }
        setFinished(res.list.length < 10)
        setPage(p)
      }
    } catch (err) {
      console.error('加载评价列表失败', err)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  // 点赞/取消点赞
  const handleLike = async (id: number) => {
    const evaluation = evaluations.find(ev => ev.id === id)
    if (!evaluation) return

    try {
      await likeShopEvaluation({
        evaluationId: id,
        isLiked: !evaluation.isLiked,
      })

      setEvaluations(prev =>
        prev.map(ev =>
          ev.id === id
            ? {
                ...ev,
                isLiked: !ev.isLiked,
                likes: ev.isLiked ? ev.likes - 1 : ev.likes + 1,
              }
            : ev
        )
      )
      Taro.showToast({ title: '操作成功', icon: 'success' })
    } catch (err) {
      console.error('点赞操作失败', err)
      Taro.showToast({ title: '操作失败', icon: 'none' })
    }
  }

  // 查看评价详情
  const handleDetail = (id: number) => {
    Taro.navigateTo({ url: `/pages/order/evaluate-detail/index?id=${id}` })
  }

  // 渲染星星
  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 sortedEvaluations = [...evaluations].sort((a, b) => {
    if (sortBy === 'newest') {
      return new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
    } else if (sortBy === 'mostLiked') {
      return b.likes - a.likes
    }
    return 0
  })

  // 加载更多
  const handleLoadMore = () => {
    if (!finished && !loading) {
      loadList(page + 1)
    }
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      {/* 排序栏 */}
      <View className='bg-white flex justify-between items-center px-3 py-2'>
        <Text className='text-sm text-gray-500'>
          共 {evaluations.length} 条评价
        </Text>
        <View className='flex gap-3'>
          <View
            className={`px-3 py-1 rounded-full text-xs ${
              sortBy === 'newest' ? 'bg-orange-500 text-white' : 'bg-gray-100 text-gray-600'
            }`}
            onClick={() => setSortBy('newest')}
          >
            <Text className={sortBy === 'newest' ? 'text-white' : 'text-gray-600'}>最新</Text>
          </View>
          <View
            className={`px-3 py-1 rounded-full text-xs ${
              sortBy === 'mostLiked' ? 'bg-orange-500 text-white' : 'bg-gray-100 text-gray-600'
            }`}
            onClick={() => setSortBy('mostLiked')}
          >
            <Text className={sortBy === 'mostLiked' ? 'text-white' : 'text-gray-600'}>最热</Text>
          </View>
        </View>
      </View>

      {/* 评价列表 */}
      <ScrollView
        scrollY
        className='flex-1'
        onScrollToLower={handleLoadMore}
        lowerThreshold={100}
      >
        <View className='p-3'>
          {evaluations.length === 0 && !loading ? (
            <EmptyState text='暂无评价' />
          ) : (
            sortedEvaluations.map(ev => (
              <View key={ev.id} className='bg-white rounded-lg p-4 mb-3 shadow-sm'>
                {/* 用户信息 */}
                <View className='flex items-center gap-2 mb-2'>
                  <View className='w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center'>
                    <Text className='text-sm text-gray-500'>{ev.isAnonymous ? '匿' : ev.userName[0]}</Text>
                  </View>
                  <View className='flex-1'>
                    <Text className='text-sm text-gray-700'>{ev.userName}</Text>
                    <View className='flex items-center gap-1'>
                      {renderStars(ev.score)}
                    </View>
                  </View>
                  <Text className='text-xs text-gray-400'>
                    {ev.createTime.split(' ')[0]}
                  </Text>
                </View>

                {/* 商品信息 */}
                <View
                  className='flex items-center gap-2 bg-gray-50 rounded-lg p-2 mb-2'
                  onClick={() => Taro.navigateTo({ url: `/pages/shop/product-detail?id=${ev.goodsId}` })}
                >
                  <View className='w-10 h-10 bg-gray-200 rounded flex items-center justify-center flex-shrink-0'>
                    <Text className='text-lg'>🛍️</Text>
                  </View>
                  <Text className='text-xs text-gray-600 flex-1'>{ev.goodsName}</Text>
                  <Text className='text-gray-400 text-xs'>→</Text>
                </View>

                {/* 评价内容 */}
                <Text className='text-sm text-gray-700 mb-2 block leading-6'>
                  {ev.content}
                </Text>

                {/* 评价图片 */}
                {ev.images && ev.images.length > 0 && (
                  <View className='flex gap-2 mb-2'>
                    {ev.images.map((img, idx) => (
                      <View key={idx} className='w-16 h-16 bg-gray-100 rounded'>
                        <Text className='text-xs text-gray-400'>图片{idx + 1}</Text>
                      </View>
                    ))}
                  </View>
                )}

                {/* 操作栏 */}
                <View className='flex items-center justify-between pt-2 border-t border-gray-50'>
                  <View
                    className={`flex items-center gap-1 ${
                      ev.isLiked ? 'opacity-100' : 'opacity-50'
                    }`}
                    onClick={() => handleLike(ev.id)}
                  >
                    <Text className={ev.isLiked ? 'text-red-500' : 'text-gray-400'}>
                      {ev.isLiked ? '❤️' : '🤍'}
                    </Text>
                    <Text className={`text-xs ${ev.isLiked ? 'text-red-500' : 'text-gray-400'}`}>
                      {ev.likes}
                    </Text>
                  </View>

                  <View
                    className='flex items-center gap-1'
                    onClick={() => handleDetail(ev.id)}
                  >
                    <Text className='text-xs text-gray-400'>查看详情</Text>
                    <Text className='text-gray-400 text-xs'>→</Text>
                  </View>
                </View>
              </View>
            ))
          )}

          <LoadMore loading={loading} finished={finished} />
        </View>
      </ScrollView>
    </View>
  )
}

export default EvaluateListPage
