import React, { useState, useEffect } 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'

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

interface HistoryItem {
  goodsId: number
  name?: string
  image?: string
  price?: string
  timestamp: number
}

const BrowseHistoryPage: React.FC = () => {
  const [list, setList] = useState<HistoryItem[]>([])

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

  const loadHistory = () => {
    try {
      const history = Taro.getStorageSync('browse_history') || []
      setList(history)
    } catch {
      setList([])
    }
  }

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

  const handleClearHistory = () => {
    Taro.showModal({
      title: '提示',
      content: '确定要清空浏览历史吗？',
      success: (res) => {
        if (res.confirm) {
          Taro.removeStorageSync('browse_history')
          setList([])
          Taro.showToast({ title: '已清空', icon: 'success' })
        }
      }
    })
  }

  const formatTime = (timestamp: number) => {
    const date = new Date(timestamp)
    return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      {/* 顶部操作栏 */}
      {list.length > 0 && (
        <View className='bg-white px-4 py-2 flex justify-end border-b border-gray-100'>
          <Text 
            className='text-sm text-red-500'
            onClick={handleClearHistory}
          >
            清空历史
          </Text>
        </View>
      )}
      
      <ScrollView scrollY className='h-screen'>
        <View className='p-3'>
          {list.length > 0 ? (
            <View className='grid grid-cols-2 gap-3'>
              {list.map(item => (
                <View
                  key={`${item.goodsId}-${item.timestamp}`}
                  className='bg-white rounded-lg overflow-hidden'
                  onClick={() => handleItemClick(item.goodsId)}
                >
                  <Image
                    className='w-full'
                    style={{ height: '160px' }}
                    src={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.timestamp)}
                      </Text>
                    </View>
                  </View>
                </View>
              ))}
            </View>
          ) : (
            <EmptyState text='暂无浏览历史' />
          )}
        </View>
      </ScrollView>
    </View>
  )
}

export default BrowseHistoryPage
