import React, { useState, useEffect, useCallback } from 'react'
import { View, Text, Image, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import EmptyState from '@/components/common/EmptyState'
import LoadMore from '@/components/common/LoadMore'
import { getCompressedImageUrl } from '@/utils/image'
import { useUserContext } from '@/contexts/UserContext'
import {
  pageBrowseHistory,
  deleteBrowseRecord,
  clearBrowseHistory
} from '@/api/shop/shopGoodsBrowse'
import type { ShopGoodsBrowseParam } from '@/api/shop/shopGoodsBrowse/model'

definePageConfig({
  navigationBarTitleText: '浏览历史',
  enablePullDownRefresh: true,
})

/** 统一展示类型（兼容服务端 + 本地兜底） */
interface DisplayItem {
  id?: number
  goodsId: number
  name?: string
  image?: string
  price?: string
  visitCount?: number
  lastVisitTime?: string
}

const PAGE_SIZE = 20

const BrowseHistoryPage: React.FC = () => {
  const { isLoggedIn } = useUserContext()
  const [list, setList] = useState<DisplayItem[]>([])
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [loading, setLoading] = useState(false)

  const loadHistory = useCallback(async (pageNum: number) => {
    if (loading) return
    setLoading(true)
    try {
      if (isLoggedIn) {
        // 已登录：服务端分页查询
        const params: ShopGoodsBrowseParam = { page: pageNum, limit: PAGE_SIZE }
        const res = await pageBrowseHistory(params)
        const items: DisplayItem[] = (res.list || []).map(item => ({
          id: item.id,
          goodsId: item.goodsId!,
          name: item.goodsName,
          image: item.goodsImage,
          price: item.price,
          visitCount: item.visitCount,
          lastVisitTime: item.lastVisitTime,
        }))
        setList(prev => pageNum === 1 ? items : [...prev, ...items])
        setHasMore(list.length + items.length < res.count)
        setPage(pageNum)
      } else {
        // 未登录：本地存储兜底
        const history = Taro.getStorageSync('browse_history') || []
        const items: DisplayItem[] = history.map((item: any) => ({
          goodsId: item.goodsId,
          name: item.name,
          image: item.image,
          price: item.price,
          lastVisitTime: item.timestamp ? new Date(item.timestamp).toISOString() : undefined,
        }))
        setList(items)
        setHasMore(false)
      }
    } catch {
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }, [isLoggedIn, loading, list.length])

  useEffect(() => {
    loadHistory(1)
  }, [isLoggedIn])

  // 下拉刷新
  const onPullDownRefresh = async () => {
    await loadHistory(1)
    Taro.stopPullDownRefresh()
  }

  // 上拉加载更多
  const onScrollToLower = () => {
    if (hasMore && !loading && isLoggedIn) {
      loadHistory(page + 1)
    }
  }

  const handleItemClick = (goodsId: number) => {
    Taro.navigateTo({ url: `/pages/shop/product-detail?id=${goodsId}` })
  }

  const handleDelete = async (item: DisplayItem) => {
    Taro.showModal({
      title: '提示',
      content: '确定要删除这条浏览记录吗？',
      success: async (res) => {
        if (res.confirm) {
          if (isLoggedIn && item.id) {
            try {
              await deleteBrowseRecord(item.id)
            } catch {
              Taro.showToast({ title: '删除失败', icon: 'none' })
              return
            }
          }
          setList(prev => prev.filter(i => i.goodsId !== item.goodsId))
          Taro.showToast({ title: '已删除', icon: 'success' })
        }
      }
    })
  }

  const handleClearHistory = () => {
    Taro.showModal({
      title: '提示',
      content: '确定要清空全部浏览历史吗？',
      success: async (res) => {
        if (res.confirm) {
          if (isLoggedIn) {
            try {
              await clearBrowseHistory()
            } catch {
              Taro.showToast({ title: '清空失败', icon: 'none' })
              return
            }
          }
          Taro.removeStorageSync('browse_history')
          setList([])
          setHasMore(false)
          Taro.showToast({ title: '已清空', icon: 'success' })
        }
      }
    })
  }

  const formatTime = (timeStr?: string) => {
    if (!timeStr) return ''
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const minutes = Math.floor(diff / 60000)
    const hours = Math.floor(diff / 3600000)
    const days = Math.floor(diff / 86400000)
    if (minutes < 1) return '刚刚'
    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`
    return `${date.getMonth() + 1}/${date.getDate()}`
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      {/* 顶部操作栏 */}
      {list.length > 0 && (
        <View className='bg-white px-4 py-2 flex justify-between items-center border-b border-gray-100'>
          <Text className='text-xs text-gray-400'>
            {isLoggedIn ? `共 ${list.length} 条记录` : '本地记录'}
          </Text>
          <Text
            className='text-sm text-red-500'
            onClick={handleClearHistory}
          >
            清空历史
          </Text>
        </View>
      )}

      <ScrollView
        scrollY
        className='h-screen'
        onScrollToLower={onScrollToLower}
        lowerThreshold={80}
      >
        <View className='p-3'>
          {list.length > 0 ? (
            <View className='grid grid-cols-2 gap-3'>
              {list.map(item => (
                <View
                  key={`${item.goodsId}-${item.id || item.lastVisitTime}`}
                  className='bg-white rounded-lg overflow-hidden relative'
                  onClick={() => handleItemClick(item.goodsId)}
                >
                  <Image
                    className='w-full'
                    style={{ height: '160px' }}
                    src={getCompressedImageUrl(item.image)}
                    mode='aspectFill'
                  />
                  <View className='p-2'>
                    <Text className='text-sm text-gray-800 line-clamp-2 block'>
                      {item.name}
                    </Text>
                    <View className='flex items-center justify-between mt-1'>
                      <Text className='text-red-500 text-sm font-medium'>
                        ¥{item.price || '0'}
                      </Text>
                      <Text className='text-xs text-gray-400'>
                        {formatTime(item.lastVisitTime)}
                      </Text>
                    </View>
                    {item.visitCount && item.visitCount > 1 && (
                      <Text className='text-xs text-orange-400 mt-1 block'>
                        浏览 {item.visitCount} 次
                      </Text>
                    )}
                  </View>
                  {/* 删除按钮 */}
                  <View
                    className='absolute top-1 right-1 w-6 h-6 rounded-full bg-black bg-opacity-40 flex items-center justify-center'
                    catchMove
                    onClick={(e) => { e.stopPropagation(); handleDelete(item) }}
                  >
                    <Text className='text-white text-xs'>×</Text>
                  </View>
                </View>
              ))}
            </View>
          ) : (
            <EmptyState text='暂无浏览历史' />
          )}
          {isLoggedIn && list.length > 0 && (
            <LoadMore hasMore={hasMore} loading={loading} />
          )}
        </View>
      </ScrollView>
    </View>
  )
}

export default BrowseHistoryPage
