<script setup lang="ts">
import type { ImApi } from '#/api/core/im';

import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue';

import { useUserStore } from '@vben/stores';

import { message } from 'ant-design-vue';

import { createGroupApi } from '#/api';
import { useImStore } from '#/store';

const userStore = useUserStore();
const imStore = useImStore();

const inputMessage = ref('');
const sending = ref(false);
const showCreateGroup = ref(false);
const showGroupManage = ref(false);
const newGroupName = ref('');
const newGroupDesc = ref('');
const selectedMemberIds = ref<string[]>([]);
const memberSearchLoading = ref(false);
const messageListRef = ref<HTMLElement | null>(null);

// Sidebar tab
const sidebarTab = ref<'contacts' | 'messages'>('messages');
const contactSearchQuery = ref('');
let contactSearchTimer: ReturnType<typeof setTimeout> | null = null;

const activeConversationId = computed(() => imStore.activeConversationId);
const activeConversation = computed(() => imStore.activeConversation);
const activeMessages = computed(() => imStore.activeMessages);

const sortedConversations = computed(() =>
  [...imStore.conversations].toSorted((a, b) => {
    const timeA = a.lastMessageAt ? new Date(a.lastMessageAt).getTime() : 0;
    const timeB = b.lastMessageAt ? new Date(a.lastMessageAt).getTime() : 0;
    return timeB - timeA;
  }),
);

function isSelfMessage(msg: ImApi.Message) {
  return msg.senderId === userStore.userInfo?.userId;
}

function formatTime(dateStr: string) {
  const date = new Date(dateStr);
  const now = new Date();
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
    });
  }
  return date.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
}

async function selectConversation(conversationId: string) {
  imStore.setActiveConversation(conversationId);
  await imStore.loadMessages(conversationId);
  await nextTick();
  scrollToBottom();
  const msgs = imStore.activeMessages;
  if (msgs.length > 0) {
    const lastMsg = msgs[msgs.length - 1];
    await imStore.markAsRead(conversationId, lastMsg.id);
  }
}

async function handleSend(e?: any) {
  if (e?.shiftKey) return;
  e?.preventDefault?.();

  const content = inputMessage.value.trim();
  if (!content || !activeConversationId.value) return;

  sending.value = true;
  try {
    await imStore.sendMessage(activeConversationId.value, 0, content);
    inputMessage.value = '';
    await nextTick();
    scrollToBottom();
  } catch {
    message.error('发送失败');
  } finally {
    sending.value = false;
  }
}

async function handleStartChat(user: ImApi.User) {
  try {
    await imStore.startPrivateChat(user.id);
    sidebarTab.value = 'messages';
    await nextTick();
    scrollToBottom();
  } catch {
    message.error('创建会话失败');
  }
}

async function handleCreateGroup() {
  if (!newGroupName.value.trim()) {
    message.warning('请输入群名称');
    return;
  }
  try {
    await createGroupApi({
      name: newGroupName.value,
      description: newGroupDesc.value || undefined,
      memberUserIds: selectedMemberIds.value,
    });
    message.success('群聊创建成功');
    showCreateGroup.value = false;
    newGroupName.value = '';
    newGroupDesc.value = '';
    selectedMemberIds.value = [];
    await imStore.loadConversations();
  } catch {
    message.error('创建失败');
  }
}

function handleContactSearch() {
  if (contactSearchTimer) clearTimeout(contactSearchTimer);
  contactSearchTimer = setTimeout(() => {
    imStore.searchContacts(contactSearchQuery.value || undefined);
  }, 300);
}

function handleMemberSearch(value: string) {
  memberSearchLoading.value = true;
  imStore.searchContacts(value || undefined).finally(() => {
    memberSearchLoading.value = false;
  });
}

function scrollToBottom() {
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
  }
}

async function onScroll() {
  if (!messageListRef.value || !activeConversationId.value) return;
  if (messageListRef.value.scrollTop === 0) {
    const msgs = imStore.activeMessages;
    const firstMsgId = msgs.length > 0 ? msgs[0].id : undefined;
    if (firstMsgId) {
      await imStore.loadMessages(activeConversationId.value, firstMsgId);
    }
  }
}

function switchToContacts() {
  sidebarTab.value = 'contacts';
  imStore.searchContacts();
}

onMounted(async () => {
  await imStore.connect();
  await imStore.loadConversations();
  await imStore.loadUnreadCounts();
});

onUnmounted(() => {
  imStore.disconnect();
});
</script>

<template>
  <div
    class="flex h-[calc(100vh-120px)] overflow-hidden rounded-lg border border-border bg-card"
  >
    <!-- Sidebar -->
    <div class="flex w-[300px] shrink-0 flex-col border-r border-border">
      <!-- Tabs -->
      <div class="flex border-b border-border">
        <div
          class="flex-1 cursor-pointer px-4 py-3 text-center text-sm transition-colors"
          :class="
            sidebarTab === 'messages'
              ? 'border-b-2 border-primary font-medium text-foreground'
              : 'text-muted-foreground hover:text-foreground'
          "
          @click="sidebarTab = 'messages'"
        >
          消息
        </div>
        <div
          class="flex-1 cursor-pointer px-4 py-3 text-center text-sm transition-colors"
          :class="
            sidebarTab === 'contacts'
              ? 'border-b-2 border-primary font-medium text-foreground'
              : 'text-muted-foreground hover:text-foreground'
          "
          @click="switchToContacts"
        >
          通讯录
        </div>
      </div>

      <!-- Messages panel -->
      <template v-if="sidebarTab === 'messages'">
        <div
          class="flex items-center justify-between border-b border-border px-4 py-2"
        >
          <span class="text-sm text-muted-foreground">
            {{ sortedConversations.length }} 个会话
          </span>
          <a-button
            type="primary"
            size="small"
            @click="showCreateGroup = true"
          >
            创建群聊
          </a-button>
        </div>
        <div class="flex-1 overflow-y-auto">
          <div
            v-for="conv in sortedConversations"
            :key="conv.id"
            class="flex cursor-pointer items-center px-4 py-3 transition-colors hover:bg-accent"
            :class="{
              'bg-primary/10 dark:bg-accent':
                conv.id === activeConversationId,
            }"
            @click="selectConversation(conv.id)"
          >
            <a-avatar v-if="conv.type === 2" :size="40">
              {{ conv.groupName?.charAt(0) || '群' }}
            </a-avatar>
            <a-avatar v-else :size="40">
              {{ conv.otherUserName?.charAt(0) || 'U' }}
            </a-avatar>

            <div class="ml-3 flex-1 overflow-hidden">
              <div class="truncate text-sm font-medium text-foreground">
                {{
                  conv.type === 2
                    ? conv.groupName
                    : conv.otherUserName || '私聊'
                }}
              </div>
              <div class="mt-1 truncate text-xs text-muted-foreground">
                {{ conv.lastMessageContent || '暂无消息' }}
              </div>
            </div>

            <a-badge
              v-if="conv.unreadCount > 0"
              :count="conv.unreadCount"
              :overflow-count="99"
            />
          </div>
        </div>
      </template>

      <!-- Contacts panel -->
      <template v-else>
        <div class="border-b border-border px-3 py-2">
          <a-input-search
            v-model:value="contactSearchQuery"
            placeholder="搜索用户名或邮箱"
            @search="imStore.searchContacts(contactSearchQuery || undefined)"
            @change="handleContactSearch"
          />
        </div>
        <div class="flex-1 overflow-y-auto">
          <a-spin :spinning="imStore.contactsLoading">
            <div
              v-for="user in imStore.contacts"
              :key="user.id"
              class="flex cursor-pointer items-center px-4 py-3 transition-colors hover:bg-accent"
              @click="handleStartChat(user)"
            >
              <a-avatar :size="40">
                {{ user.username.charAt(0).toUpperCase() }}
              </a-avatar>
              <div class="ml-3 flex-1 overflow-hidden">
                <div class="truncate text-sm font-medium text-foreground">
                  {{ user.username }}
                </div>
                <div class="mt-1 truncate text-xs text-muted-foreground">
                  {{ user.email }}
                </div>
              </div>
              <span
                v-if="imStore.onlineUsers.has(user.id)"
                class="mr-2 inline-block h-2 w-2 rounded-full bg-green-500"
              />
            </div>
            <div
              v-if="
                !imStore.contactsLoading && imStore.contacts.length === 0
              "
              class="px-4 py-8 text-center text-sm text-muted-foreground"
            >
              没有找到用户
            </div>
          </a-spin>
        </div>
      </template>
    </div>

    <!-- Main chat area -->
    <div class="flex flex-1 flex-col">
      <template v-if="activeConversation">
        <div
          class="flex items-center justify-between border-b border-border px-4 py-3 font-medium text-foreground"
        >
          <span>
            {{
              activeConversation.type === 2
                ? activeConversation.groupName
                : activeConversation.otherUserName || '私聊'
            }}
          </span>
          <a-button
            v-if="activeConversation.type === 2"
            size="small"
            @click="showGroupManage = true"
          >
            群管理
          </a-button>
        </div>

        <div
          ref="messageListRef"
          class="flex-1 overflow-y-auto px-4 py-4"
          @scroll="onScroll"
        >
          <div
            v-for="msg in activeMessages"
            :key="msg.id"
            class="mb-4"
            :class="{ 'text-right': isSelfMessage(msg) }"
          >
            <div class="mb-1 text-xs text-muted-foreground">
              {{ msg.senderName || msg.senderId.substring(0, 8) }}
            </div>
            <div
              class="inline-block max-w-[60%] break-words rounded-lg px-3 py-2"
              :class="
                isSelfMessage(msg)
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-muted text-foreground'
              "
            >
              <template v-if="msg.contentType === 0">
                {{ msg.content }}
              </template>
              <template v-else-if="msg.contentType === 1">
                <img
                  :src="msg.metadata?.imageUrl"
                  class="max-w-[200px] rounded-lg"
                />
              </template>
              <template v-else-if="msg.contentType === 4">
                <span class="text-2xl">{{ msg.content }}</span>
              </template>
              <template v-else>
                [{{
                  ['文本', '图片', '文件', '系统', '表情'][msg.contentType]
                }}]
              </template>
            </div>
            <div class="mt-1 text-[11px] text-muted-foreground/60">
              {{ formatTime(msg.createdAt) }}
            </div>
          </div>
        </div>

        <div class="flex gap-2 border-t border-border px-4 py-3">
          <a-textarea
            v-model:value="inputMessage"
            placeholder="输入消息..."
            :auto-size="{ minRows: 1, maxRows: 4 }"
            @press-enter="handleSend"
          />
          <a-button type="primary" @click="handleSend" :loading="sending">
            发送
          </a-button>
        </div>
      </template>

      <div
        v-else
        class="flex flex-1 items-center justify-center text-muted-foreground"
      >
        <p>选择一个会话开始聊天</p>
      </div>
    </div>

    <!-- Create Group Modal -->
    <a-modal
      v-model:open="showCreateGroup"
      title="创建群聊"
      @ok="handleCreateGroup"
    >
      <a-form layout="vertical">
        <a-form-item label="群名称">
          <a-input v-model:value="newGroupName" />
        </a-form-item>
        <a-form-item label="群描述">
          <a-input v-model:value="newGroupDesc" />
        </a-form-item>
        <a-form-item label="选择成员">
          <a-select
            v-model:value="selectedMemberIds"
            mode="multiple"
            placeholder="搜索并选择成员"
            :filter-option="false"
            :loading="memberSearchLoading"
            @search="handleMemberSearch"
          >
            <a-select-option
              v-for="user in imStore.contacts"
              :key="user.id"
              :value="user.id"
            >
              {{ user.username }} ({{ user.email }})
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
