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

definePageConfig({
  navigationBarTitleText: '消息详情',
})

const MessageDetailPage: React.FC = () => {
  const { id } = Taro.getCurrentInstance().router?.params || {}
  const [message, setMessage] = useState<ShopMessage | null>(null)
  const [loading, setLoading] = useState(true)

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

  const fetchMessage = async (msgId: string) => {
    try {
      const res = await getShopMessage(msgId)
      if (res?.code === 0 && res.data) {
        setMessage(res.data)
      }
    } catch (err: any) {
      Taro.showToast({ title: err.message || '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  // 获取类型图标
  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 year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  }

  // 删除消息
  const handleDelete = () => {
    if (!message) return
    Taro.showModal({
      title: '提示',
      content: '确定删除该消息吗？',
      confirmColor: '#0e932e',
      success: async (res) => {
        if (res.confirm) {
          try {
            await deleteShopMessage(message.id)
            Taro.showToast({ title: '删除成功', icon: 'success' })
            setTimeout(() => Taro.navigateBack(), 1500)
          } catch (err: any) {
            Taro.showToast({ title: err.message || '删除失败', icon: 'none' })
          }
        }
      }
    })
  }

  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 (!message) {
    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='min-h-screen bg-gray-50 flex flex-col'>
      <ScrollView scrollY className='flex-1'>
        {/* 消息头部 */}
        <View className='bg-white p-4 mb-3'>
          <View className='flex items-center gap-2 mb-3'>
            <Text className='text-2xl'>{getTypeIcon(message.type)}</Text>
            <View className='flex-1'>
              <Text className='text-lg font-bold text-gray-800 block mb-1'>
                {message.title}
              </Text>
              <View className='flex items-center gap-2'>
                <Text className='text-xs text-gray-400'>
                  {formatTime(message.createdAt)}
                </Text>
                <View className='bg-gray-100 px-2 py-1 rounded'>
                  <Text className='text-xs text-gray-500'>
                    {getTypeName(message.type)}
                  </Text>
                </View>
              </View>
            </View>
          </View>
        </View>

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

        {/* 相关操作 */}
        <View className='bg-white p-4'>
          <Text className='text-sm font-medium text-gray-800 mb-3 block'>相关操作</Text>
          <View className='flex flex-col gap-3'>
            <View
              className='flex items-center justify-between py-2 border-b border-gray-50'
              onClick={() => Taro.navigateTo({ url: '/pages/user/user' })}
            >
              <Text className='text-sm text-gray-600'>查看个人中心</Text>
              <Text className='text-gray-400'>→</Text>
            </View>
            <View
              className='flex items-center justify-between py-2 border-b border-gray-50'
              onClick={() => Taro.switchTab({ url: '/pages/index/index' })}
            >
              <Text className='text-sm text-gray-600'>返回首页</Text>
              <Text className='text-gray-400'>→</Text>
            </View>
            <View
              className='flex items-center justify-between py-2'
              onClick={handleDelete}
            >
              <Text className='text-sm text-red-500'>删除此消息</Text>
              <Text className='text-gray-400'>→</Text>
            </View>
          </View>
        </View>

        <View className='h-6' />
      </ScrollView>
    </View>
  )
}

export default MessageDetailPage
