<template>
  <FlexCol 
    flex="1"
    radius="radius.md"
    backgroundColor="background.white"
    width="100%"
    height="100%"
  >
    <LoadingPage v-if="sessionManager.sessionsLoading.value" />
    <scroll-view 
      scroll-y
      :style="{ height: '100%' }"
      refresher-enabled
      :refresher-triggered="sessionManager.sessionsLoading.value"
      @refresherrefresh="sessionManager.loadSessions()"
    >
      <FlexCol padding="space.md" gap="gap.md">
        <slot name="header"></slot>
        <SearchBar 
          v-model="sessionManager.searchSession.value"
          inputBackgroundColor="background.bar"
          placeholder="搜索会话"
          @clear="sessionManager.loadSessions()"
          @search="sessionManager.loadSessions()"
        />
        <ChatSessionSidebarItem 
          name="new" 
          desc="新对话" 
          icon="chat-dot" 
          rightIcon="add"
          :showMore="false"
          @click="onMenuClick('new')"
        />
        <ChatSessionSidebarItem 
          name="local" 
          desc="临时会话" 
          title="开启临时会话，不会保存聊天记录" 
          icon="chat" 
          rightIcon="arrow-right"
          :showMore="false"
          @click="onMenuClick('local')"
        />
        <ChatSessionSidebarGroupHeader title="历史会话" />
        <template v-for="group in sessionList" :key="group.key">
          <ChatSessionSidebarGroupHeader :title="group.title" :desc="group.date" second />
          <ChatSessionSidebarItem
            v-for="s in group.items"
            :key="String(s.id)"
            :name="String(s.id)"
            :desc="s.desc || '未命名'"
            icon="chat-double"
            showMore
            @click="onMenuClick(String(s.id))"
            @moreClick="onMoreClick(s as AgentChatHistory)"
          />
        </template>
        <ChatSessionSidebarEmpty v-if="sessionList.length === 0" />
        <ChatSessionSidebarLoadMore v-if="sessionList.length > 0" 
          :loading="sessionManager.sessionsLoading.value" 
          :hasMore="sessionManager.sessionsHasMore.value" 
          @loadMore="sessionManager.loadMoreSessions()"
        />
      </FlexCol>
    </scroll-view>

    <!--重命名会话-->
    <ChatSessionRenameDialog :session-manager="sessionManager" />
  </FlexCol>
</template>

<script setup lang="ts">
import { computed, provide } from 'vue';
import { CHAT_SESSION_LOCAL_ID, CHAT_SESSION_NEW_ID, type ChatSessionManager } from '../../composables/useChatSession';
import { DateUtils, TimeUtils } from '@imengyu/imengyu-utils';
import { actionSheet } from '@/components/dialog/CommonRoot';
import ChatSessionSidebarItem from './ChatSessionSidebarItem.vue';
import ChatSessionSidebarGroupHeader from './ChatSessionSidebarGroupHeader.vue';
import ChatSessionSidebarEmpty from './ChatSessionSidebarEmpty.vue';
import ChatSessionSidebarLoadMore from './ChatSessionSidebarLoadMore.vue';
import ChatSessionRenameDialog from './ChatSessionRenameDialog.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import LoadingPage from '@/components/display/loading/LoadingPage.vue';
import SearchBar from '@/components/form/SearchBar.vue';
import type { AgentChatHistory } from '@/api/agent/Agent';

const props = withDefaults(defineProps<{
  sessionManager: ChatSessionManager;
}>(), {
});

const emit = defineEmits(['close']);

const selectedKeys = computed(() => {
  switch (props.sessionManager.currentSessionId.value) {
    case CHAT_SESSION_NEW_ID:
      return ['new'];
    case CHAT_SESSION_LOCAL_ID:
      return ['local'];
    default:
      return [String(props.sessionManager.currentSessionId.value)];
  }
});

provide('selectedKeys', selectedKeys);

type SessionDateGroup = {
  key: string;
  title: string;
  date: string,
  items: SessionListItem[];
}

type SessionListItem = (typeof props.sessionManager.sessions.value)[number];

const sessionList = computed<SessionDateGroup[]>(() => {
  const groups = new Map<string, SessionDateGroup>();
  for (const session of props.sessionManager.sessions.value) {
    const date = session.createdAt;
    const key = DateUtils.formatDate(date, 'YYYY-MM-DD');
    const title = TimeUtils.getTimeAgo(date)!;
    const existing = groups.get(key);
    if (existing) {
      existing.items.push(session);
      continue;
    }
    groups.set(key, {
      key,
      title,
      date: DateUtils.formatDate(date, 'YYYY-MM-DD HH:mm'),
      items: [session],
    });
  }
  return Array.from(groups.values());
});

async function onMoreClick(row: AgentChatHistory) {
  const res = await actionSheet({
    showCancel: true,
    actions: [
      {
        name: '重命名',
      },
      {
        name: '删除会话',
        color: 'error',
      },
    ],
  });
  if (res === undefined) 
    return;
  switch (res) {
    case 0:
      props.sessionManager.onRenameSession(row);
      break;
    case 1:
      props.sessionManager.onDeleteSession(row);
      break;
  }
}
function onMenuClick(key: string) {
  switch (key) {
    case 'new':
      props.sessionManager.onSelectNew();
      break;
    case 'local':
      props.sessionManager.onSelectLocal();
      break;
    default:
      props.sessionManager.onSelectSession(Number(key));
  }
  emit('close');
}
</script>
