<script setup>
import { computed, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useDeviceStore } from '@/stores/deviceStore'
import { useChatStore } from '@/stores/chatStore'
import { chatApi } from '@/api'
import { Search, RefreshCw, Monitor, Smartphone, Laptop, ScanLine } from 'lucide-vue-next'

const router = useRouter()
const deviceStore = useDeviceStore()
const chatStore = useChatStore()

const searchQuery = ref('')
const isRefreshing = ref(false)
const conversations = ref([])

// 合并会话列表和在线设备（没有聊天记录的新设备也显示）
const mergedList = computed(() => {
  const result = []
  const conversationDeviceIds = new Set()
  
  // 首先添加所有有聊天记录的会话
  for (const conv of conversations.value) {
    conversationDeviceIds.add(conv.deviceId)
    // 检查是否在线
    const isOnline = deviceStore.devices.has(conv.deviceId)
    result.push({
      ...conv,
      online: isOnline,
      // 如果在线，从 deviceStore 获取最新信息
      ...(isOnline ? { ip: deviceStore.devices.get(conv.deviceId)?.ip || conv.ip } : {})
    })
  }
  
  // 然后添加在线但没有聊天记录的新设备
  for (const device of deviceStore.deviceList) {
    if (!conversationDeviceIds.has(device.deviceId)) {
      result.push({
        deviceId: device.deviceId,
        deviceName: device.deviceName,
        ip: device.ip,
        online: true,
        lastMessage: null,
        lastMessageType: null,
        lastMessageTime: null,
        unreadCount: 0,
        isNewDevice: true  // 标记为新设备
      })
    }
  }
  
  // 按：在线设备优先，然后按最后消息时间排序
  result.sort((a, b) => {
    // 在线设备优先
    if (a.online !== b.online) return b.online ? 1 : -1
    // 然后按最后消息时间
    const timeA = a.lastMessageTime || 0
    const timeB = b.lastMessageTime || 0
    return timeB - timeA
  })
  
  return result
})

// 过滤列表
const filteredList = computed(() => {
  const query = searchQuery.value.toLowerCase().trim()
  if (!query) return mergedList.value
  
  return mergedList.value.filter(item =>
    item.deviceName.toLowerCase().includes(query) ||
    item.ip.includes(query)
  )
})

// 根据设备名推断图标
function getDeviceIcon(name) {
  const n = name.toLowerCase()
  if (n.includes('phone') || n.includes('mobile') || n.includes('android') || n.includes('iphone')) {
    return Smartphone
  }
  if (n.includes('laptop') || n.includes('macbook') || n.includes('notebook')) {
    return Laptop
  }
  return Monitor
}

// 格式化时间
function formatTime(timestamp) {
  if (!timestamp) return ''
  
  const date = new Date(timestamp * 1000)
  const now = new Date()
  const diff = now - date
  
  // 今天内显示时间
  if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
  
  // 昨天
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.getDate() === yesterday.getDate()) {
    return '昨天'
  }
  
  // 一周内显示星期
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    return days[date.getDay()]
  }
  
  // 更早的显示日期
  return `${date.getMonth() + 1}/${date.getDate()}`
}

// 格式化最后消息预览
function formatLastMessage(item) {
  if (!item.lastMessage) {
    return item.isNewDevice ? '新发现的设备' : '暂无消息'
  }
  
  // 文件消息
  if (item.lastMessageType === 'file') {
    return item.lastMessage.replace(/^📎\s*/, '[文件] ')
  }
  
  // 图片消息
  if (item.lastMessageType === 'image') {
    return '[图片]'
  }
  
  // 普通文本，截断过长的
  const text = item.lastMessage
  return text.length > 30 ? text.substring(0, 30) + '...' : text
}

// 打开聊天
async function openChat(item) {
  // 如果在线且未连接，先连接
  if (item.online && !deviceStore.isConnected(item.deviceId)) {
    try {
      await deviceStore.connectToDevice(item.deviceId)
    } catch (error) {
      console.error('Connection failed:', error)
    }
  }
  router.push(`/chat/${item.deviceId}`)
}

// 刷新
async function refresh() {
  if (isRefreshing.value) return
  
  isRefreshing.value = true
  try {
    await deviceStore.stopServices()
    await deviceStore.startServices()
    await loadConversations()
  } finally {
    setTimeout(() => {
      isRefreshing.value = false
    }, 1000)
  }
}

// 加载会话列表
async function loadConversations() {
  try {
    conversations.value = await chatApi.getConversations()
  } catch (error) {
    console.error('Failed to load conversations:', error)
  }
}

onMounted(() => {
  loadConversations()
})
</script>

<template>
  <div class="h-full flex flex-col bg-surface-50 dark:bg-surface-900">
    <!-- 头部 -->
    <header class="flex-shrink-0 bg-white dark:bg-surface-800 border-b border-surface-200 dark:border-surface-700">
      <!-- 标题栏 -->
      <div class="flex items-center justify-between px-4 py-3">
        <h1 class="text-lg font-semibold text-surface-900 dark:text-white">消息</h1>
        <div class="flex items-center gap-2">
          <button
            @click="refresh"
            class="p-2 rounded-lg hover:bg-surface-100 dark:hover:bg-surface-700 text-surface-500 dark:text-surface-400 transition-colors"
            :class="{ 'cursor-not-allowed opacity-50': isRefreshing }"
            :disabled="isRefreshing"
            title="刷新"
          >
            <RefreshCw :size="20" :class="{ 'animate-spin': isRefreshing }" />
          </button>
        </div>
      </div>
      
      <!-- 搜索框 -->
      <div class="px-4 pb-3">
        <div class="relative">
          <Search class="absolute left-3 top-1/2 -translate-y-1/2 text-surface-400" :size="18" />
          <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索"
            class="w-full pl-10 pr-4 py-2 bg-surface-100 dark:bg-surface-700 border-none rounded-lg text-sm text-surface-900 dark:text-white placeholder-surface-400 focus:outline-none focus:ring-2 focus:ring-primary-500/50"
          />
        </div>
      </div>
    </header>

    <!-- 会话列表 -->
    <div class="flex-1 overflow-y-auto">
      <!-- 发现设备提示 -->
      <div 
        v-if="deviceStore.isDiscovering && deviceStore.deviceCount === 0 && filteredList.length === 0"
        class="flex flex-col items-center justify-center h-48 text-surface-400"
      >
        <div class="relative mb-4">
          <ScanLine :size="48" class="animate-pulse" />
        </div>
        <p class="text-sm">正在搜索附近设备...</p>
      </div>

      <!-- 空状态 -->
      <div 
        v-else-if="filteredList.length === 0"
        class="flex flex-col items-center justify-center h-48 text-surface-400"
      >
        <Monitor :size="48" class="mb-4 opacity-50" />
        <p class="text-sm">{{ searchQuery ? '未找到匹配的设备' : '暂无会话' }}</p>
      </div>

      <!-- 列表 -->
      <div v-else>
        <div
          v-for="item in filteredList"
          :key="item.deviceId"
          @click="openChat(item)"
          class="flex items-center gap-3 px-4 py-3 hover:bg-surface-100 dark:hover:bg-surface-800 cursor-pointer transition-colors border-b border-surface-100 dark:border-surface-800 last:border-b-0"
        >
          <!-- 头像/图标 -->
          <div class="relative flex-shrink-0">
            <div 
              class="w-12 h-12 rounded-lg flex items-center justify-center"
              :class="item.online 
                ? 'bg-primary-100 dark:bg-primary-900/30 text-primary-600 dark:text-primary-400' 
                : 'bg-surface-200 dark:bg-surface-700 text-surface-400'"
            >
              <component :is="getDeviceIcon(item.deviceName)" :size="24" />
            </div>
            <!-- 在线状态点 -->
            <span 
              v-if="item.online"
              class="absolute -bottom-0.5 -right-0.5 w-3.5 h-3.5 bg-green-500 rounded-full border-2 border-white dark:border-surface-900"
            />
          </div>

          <!-- 信息 -->
          <div class="flex-1 min-w-0">
            <div class="flex items-center justify-between mb-0.5">
              <span class="font-medium text-surface-900 dark:text-white truncate">
                {{ item.deviceName }}
              </span>
              <span class="text-xs text-surface-400 flex-shrink-0 ml-2">
                {{ formatTime(item.lastMessageTime) }}
              </span>
            </div>
            <div class="flex items-center justify-between">
              <p 
                class="text-sm truncate"
                :class="item.lastMessage ? 'text-surface-500 dark:text-surface-400' : 'text-surface-400 dark:text-surface-500 italic'"
              >
                {{ formatLastMessage(item) }}
              </p>
              <!-- 未读数 -->
              <span 
                v-if="item.unreadCount > 0 || chatStore.getUnreadCount(item.deviceId) > 0"
                class="flex-shrink-0 ml-2 min-w-[20px] h-5 px-1.5 bg-red-500 text-white text-xs font-medium rounded-full flex items-center justify-center"
              >
                {{ (item.unreadCount || chatStore.getUnreadCount(item.deviceId)) > 99 ? '99+' : (item.unreadCount || chatStore.getUnreadCount(item.deviceId)) }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部状态 -->
    <footer class="flex-shrink-0 px-4 py-2 bg-white dark:bg-surface-800 border-t border-surface-200 dark:border-surface-700">
      <div class="flex items-center justify-between text-xs text-surface-400">
        <div class="flex items-center gap-2">
          <span class="flex items-center gap-1">
            <span class="w-2 h-2 rounded-full bg-green-500"></span>
            {{ deviceStore.deviceCount }} 台在线
          </span>
        </div>
        <span v-if="deviceStore.localDevice" class="font-mono">
          {{ deviceStore.localDevice.ip }}
        </span>
      </div>
    </footer>
  </div>
</template>
