<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useDeviceStore } from '@/stores/deviceStore'
import { useChatStore } from '@/stores/chatStore'
import MessageBubble from '@/components/MessageBubble.vue'
import ChatInput from '@/components/ChatInput.vue'
import FileProgress from '@/components/FileProgress.vue'
import { ArrowLeft, MoreVertical, Trash2 } from 'lucide-vue-next'

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

const deviceId = computed(() => route.params.deviceId)
const device = computed(() => deviceStore.getDevice(deviceId.value))
const messages = computed(() => chatStore.messages.get(deviceId.value) || [])
const localDeviceId = computed(() => deviceStore.localDevice?.deviceId || '')

// 只显示与当前对话设备相关的、进行中的传输记录（完成后隐藏）
const deviceTransfers = computed(() => {
  const result = []
  chatStore.transfers.forEach((transfer, id) => {
    // 我发送给对方 或 对方发送给我
    const isRelevant = 
      (transfer.fromDevice === localDeviceId.value && transfer.toDevice === deviceId.value) ||
      (transfer.fromDevice === deviceId.value && transfer.toDevice === localDeviceId.value)
    // 只显示进行中的传输（pending 或 transferring）
    const isInProgress = transfer.status === 'pending' || transfer.status === 'transferring'
    if (isRelevant && isInProgress) {
      result.push([id, transfer])
    }
  })
  return result
})

const messagesContainer = ref(null)
const showMenu = ref(false)

// 滚动到底部
function scrollToBottom() {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 发送消息
async function sendMessage(content) {
  try {
    await chatStore.sendMessage(deviceId.value, content)
    scrollToBottom()
  } catch (error) {
    console.error('Failed to send message:', error)
  }
}

// 选择文件
async function selectFile() {
  const file = await chatStore.selectFile()
  if (file && device.value) {
    // 发送文件，同时发送一条文件消息到聊天记录
    await chatStore.sendFile(deviceId.value, file)
    // 发送文件消息，让接收方也能在聊天记录中看到
    await chatStore.sendMessage(
      deviceId.value,
      `📎 ${file.name}`,
      'file'
    )
  }
}

// 删除聊天记录
async function deleteHistory() {
  showMenu.value = false
  const { ask } = await import('@tauri-apps/plugin-dialog')
  const confirmed = await ask('确定要删除所有聊天记录吗？', {
    title: '删除确认',
    kind: 'warning'
  })
  if (confirmed) {
    await chatStore.deleteHistory(deviceId.value)
  }
}

// 返回
function goBack() {
  router.push('/devices')
}

// 点击文件消息，打开文件位置（仅接收方有效）
async function handleFileClick(fileName) {
  // 先在内存中查找
  for (const [, transfer] of chatStore.transfers) {
    // 接收到的文件（toDevice 是本机）
    if (transfer.name === fileName && transfer.toDevice === localDeviceId.value && transfer.localPath) {
      await chatStore.openFileLocation(transfer.localPath)
      return
    }
  }
  
  // 内存中没有或 localPath 为空，强制从数据库加载
  await chatStore.loadTransferHistory(deviceId.value, true)
  for (const [, transfer] of chatStore.transfers) {
    if (transfer.name === fileName && transfer.toDevice === localDeviceId.value && transfer.localPath) {
      await chatStore.openFileLocation(transfer.localPath)
      return
    }
  }
  
  console.log('File not found:', fileName)
}

// 监听新消息
watch(messages, () => {
  scrollToBottom()
}, { deep: true })

onMounted(async () => {
  chatStore.setCurrentDevice(deviceId.value)
  
  // 确保已连接
  if (!deviceStore.isConnected(deviceId.value)) {
    try {
      await deviceStore.connectToDevice(deviceId.value)
    } catch (error) {
      console.error('Connection failed:', error)
    }
  }
  
  // 加载历史记录
  await chatStore.loadHistory(deviceId.value)
  // 加载传输历史（用于点击文件消息时打开文件）
  await chatStore.loadTransferHistory(deviceId.value)
  scrollToBottom()
})

onUnmounted(() => {
  chatStore.setCurrentDevice(null)
})
</script>

<template>
  <div class="h-full flex flex-col bg-surface-50 dark:bg-gray-900">
    <!-- 头部 -->
    <header class="bg-white dark:bg-gray-800 border-b border-surface-200 dark:border-gray-700 px-4 py-3 flex items-center gap-3">
      <button
        @click="goBack"
        class="p-2 rounded-lg hover:bg-surface-100 dark:hover:bg-gray-700 text-gray-500 dark:text-gray-400 transition-colors"
      >
        <ArrowLeft :size="20" />
      </button>

      <div class="flex-1 min-w-0">
        <h2 class="font-medium text-gray-900 dark:text-white truncate">
          {{ device?.deviceName || '未知设备' }}
        </h2>
        <p class="text-sm text-gray-500 dark:text-gray-400">
          {{ device?.ip }}
          <span 
            class="inline-block w-2 h-2 rounded-full ml-2"
            :class="deviceStore.isConnected(deviceId) ? 'bg-green-500' : 'bg-gray-300 dark:bg-gray-600'"
          />
        </p>
      </div>

      <!-- 更多菜单 -->
      <div class="relative">
        <button
          @click="showMenu = !showMenu"
          class="p-2 rounded-lg hover:bg-surface-100 dark:hover:bg-gray-700 text-gray-500 dark:text-gray-400 transition-colors"
        >
          <MoreVertical :size="20" />
        </button>

        <div 
          v-if="showMenu"
          class="absolute right-0 top-full mt-1 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-surface-200 dark:border-gray-700 py-1 z-10"
        >
          <button
            @click="deleteHistory"
            class="w-full px-4 py-2 text-left text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 flex items-center gap-2"
          >
            <Trash2 :size="16" />
            删除聊天记录
          </button>
        </div>
      </div>
    </header>

    <!-- 消息列表 -->
    <div 
      ref="messagesContainer"
      class="flex-1 overflow-y-auto px-4 py-4"
    >
      <!-- 空状态 -->
      <div 
        v-if="messages.length === 0"
        class="h-full flex flex-col items-center justify-center text-gray-400 dark:text-gray-500"
      >
        <p>暂无消息</p>
        <p class="text-sm mt-1">发送消息开始聊天</p>
      </div>

      <!-- 消息列表 -->
      <template v-else>
        <MessageBubble
          v-for="message in messages"
          :key="message.id"
          :message="message"
          :is-sent="message.from === localDeviceId"
          @file-click="handleFileClick"
        />
      </template>
    </div>

    <!-- 文件传输进度（只显示与当前设备相关的） -->
    <div 
      v-if="deviceTransfers.length > 0"
      class="px-4 pb-2 space-y-2"
    >
      <FileProgress
        v-for="[id, transfer] in deviceTransfers"
        :key="id"
        :transfer="transfer"
        :is-receiver="transfer.toDevice === localDeviceId"
        @open="chatStore.openFileLocation(transfer.localPath || '')"
        @cancel="chatStore.cancelTransfer"
      />
    </div>

    <!-- 输入区域 -->
    <ChatInput
      @send="sendMessage"
      @select-file="selectFile"
      @select-image="selectFile"
    />
  </div>
</template>
