import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { listShopMessage, readShopMessage, deleteShopMessage, readAllShopMessage } from '@/api/shop/shopMessage'
import type { ShopMessage, MessageType } from '@/api/shop/shopMessage'

definePageConfig({
  navigationBarTitleText: '消息通知',
})

// 消息类型
const messageTypes = [
  { label: '全部', value: '' },
  { label: '系统通知', value: 'system' },
  { label: '订单通知', value: 'order' },
  { label: '活动通知', value: 'activity' },
]

const MessageListPage: React.FC = () => {
  const [activeType, setActiveType] = useState<string>('')
  const [messages, setMessages] = useState<ShopMessage[]>([])
  const [loading, setLoading] = useState(false)
  const [finished, setFinished] = useState(false)
  const [page, setPage] = useState(1)

  useEffect(() => {
    setMessages([])
    setPage(1)
    setFinished(false)
    loadList(1)
  }, [activeType])

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

    try {
      const params: any = {
        page: p,
        limit: 10,
      }
      if (activeType) {
        params.type = activeType
      }

      const res = await listShopMessage(params)

      if (res?.list) {
        if (p === 1) {
          setMessages(res.list)
        } else {
          setMessages(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 handleLoadMore = () => {
    if (!finished && !loading) {
      loadList(page + 1)
    }
  }

  // 标记已读
  const markAsRead = async (id: string) => {
    try {
      await readShopMessage(id)
      setMessages(prev =>
        prev.map(msg =>
          msg.id === id ? { ...msg, isRead: true } : msg
        )
      )
      Taro.navigateTo({ url: `/pages/message/detail/index?id=${id}` })
    } catch (err) {
      console.error('标记已读失败', err)
    }
  }

  // 删除消息
  const deleteMessage = (id: string) => {
    Taro.showModal({
      title: '提示',
      content: '确定删除该消息吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            await deleteShopMessage(id)
            setMessages(prev => prev.filter(msg => msg.id !== id))
            Taro.showToast({ title: '删除成功', icon: 'success' })
          } catch (err) {
            console.error('删除消息失败', err)
            Taro.showToast({ title: '删除失败', icon: 'none' })
          }
        }
      }
    })
  }

  // 全部标记为已读
  const markAllAsRead = () => {
    Taro.showModal({
      title: '提示',
      content: '确定将所有消息标记为已读吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            await readAllShopMessage()
            setMessages(prev =>
              prev.map(msg => ({ ...msg, isRead: true }))
            )
            Taro.showToast({ title: '已全部标为已读', icon: 'success' })
          } catch (err) {
            console.error('全部标记已读失败', err)
            Taro.showToast({ title: '操作失败', icon: 'none' })
          }
        }
      }
    })
  }

  // 获取类型图标
  const getTypeIcon = (type: MessageType) => {
    const iconMap: Record<MessageType, string> = {
      'system': '🔔',
      'order': '📦',
      'activity': '🎁',
    }
    return iconMap[type] || '📋'
  }

  // 获取类型名称
  const getTypeName = (type: MessageType) => {
    const nameMap: Record<MessageType, string> = {
      'system': '系统',
      'order': '订单',
      'activity': '活动',
    }
    return nameMap[type] || '其他'
  }

  // 格式化时间
  const formatTime = (timeStr: string) => {
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (days === 0) {
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `今天 ${hours}:${minutes}`
    } else if (days === 1) {
      return '昨天'
    } else if (days < 7) {
      return `${days}天前`
    } else {
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${month}-${day}`
    }
  }

  return (
    <View className='min-h-screen bg-gray-50 flex flex-col'>
      {/* 顶部操作栏 */}
      <View className='bg-white px-3 py-2 flex justify-between items-center border-b border-gray-100'>
        <Text className='text-sm text-gray-500'>
          共 {messages.length} 条消息
        </Text>
        <View onClick={markAllAsRead}>
          <Text className='text-sm text-orange-500'>全部已读</Text>
        </View>
      </View>

      {/* 分类标签 */}
      <View className='bg-white flex overflow-x-auto'>
        {messageTypes.map(type => (
          <View
            key={type.value}
            className={`flex-shrink-0 px-4 py-3 relative ${
              activeType === type.value ? 'text-orange-500 font-medium' : 'text-gray-600'
            }`}
            onClick={() => setActiveType(type.value)}
          >
            <Text className='text-sm'>{type.label}</Text>
            {activeType === type.value && (
              <View className='absolute bottom-0 w-8 h-px bg-orange-500 rounded' style={{ left: '50%', transform: 'translateX(-50%)' }} />
            )}
          </View>
        ))}
      </View>

      {/* 消息列表 */}
      <ScrollView scrollY className='flex-1'>
        {messages.length === 0 ? (
          <View className='text-center py-16'>
            <Text className='text-4xl mb-3 block'>📭</Text>
            <Text className='text-sm text-gray-400'>暂无消息通知</Text>
          </View>
        ) : (
          <View className='p-3'>
            {messages.map(message => (
              <View
                key={message.id}
                className={`bg-white rounded-lg p-4 mb-3 relative ${
                  !message.isRead ? 'border-l-4 border-orange-500' : ''
                }`}
                onClick={() => markAsRead(message.id)}
              >
                {/* 未读标识 */}
                {!message.isRead && (
                  <View className='absolute top-4 right-4 w-2 h-2 bg-red-500 rounded-full' />
                )}

                {/* 消息头部 */}
                <View className='flex items-center gap-2 mb-2'>
                  <Text className='text-lg'>{getTypeIcon(message.type)}</Text>
                  <Text className='text-sm font-medium text-gray-800 flex-1'>
                    {message.title}
                  </Text>
                  <Text className='text-xs text-gray-400'>
                    {formatTime(message.createdAt)}
                  </Text>
                </View>

                {/* 消息内容 */}
                <Text className='text-sm text-gray-600 mb-2 block ml-7'>
                  {message.content}
                </Text>

                {/* 消息底部 */}
                <View className='flex items-center justify-between ml-7'>
                  <View className='bg-gray-100 px-2 py-1 rounded'>
                    <Text className='text-xs text-gray-500'>
                      {getTypeName(message.type)}
                    </Text>
                  </View>
                  <View onClick={(e) => {
                    e.stopPropagation()
                    deleteMessage(message.id)
                  }}>
                    <Text className='text-xs text-gray-400'>删除</Text>
                  </View>
                </View>
              </View>
            ))}
          </View>
        )}
      </ScrollView>
    </View>
  )
}

export default MessageListPage
