import { create } from 'zustand';
import type { Session } from '@/types/session';
import type { Message } from '@/types/chat';
import {
  fetchSessions,
  fetchMessages,
  createSession as apiCreateSession,
  deleteSession as apiDeleteSession,
  deleteAllSessions as apiDeleteAllSessions,
  clearSessionMessages as apiClearMessages,
} from '@/api/sessions';
import { useChatStore } from '@/store/chatStore';

/** 生成简易随机ID */
function randomID(n: number = 12): string {
  const letters = 'abcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < n; i++) {
    result += letters.charAt(Math.floor(Math.random() * letters.length));
  }
  return `session_${result}`;
}

/** 判断是否为管理员用户 (user_id 为固定值 "admin") */
export function isAdminUser(userId: string | null): boolean {
  return userId === 'admin';
}

/** 每页加载的消息数量 */
const PAGE_SIZE = 50;

interface SessionStore {
  sessions: Session[];
  currentSessionId: string | null;
  loading: boolean;
  messages: Message[];

  // 防止竞态条件的请求版本号 (每次 setCurrentSessionId 时递增)
  _loadVersion: number;

  // 基础操作
  setSessions: (sessions: Session[]) => void;
  addSession: (session: Session) => void;
  removeSession: (id: string) => void;
  setCurrentSessionId: (id: string | null) => void;
  setLoading: (loading: boolean) => void;
  setMessages: (messages: Message[]) => void;
  clearMessages: () => void;

  // 服务端持久化操作
  loadSessionsFromServer: (userId: string) => Promise<void>;
  loadMessagesFromServer: (sessionId: string) => Promise<void>;
  loadMoreMessagesFromServer: (sessionId: string) => Promise<void>;
  clearMainSessionMessages: (sessionId: string) => Promise<boolean>;
  deleteSessionAndRefresh: (id: string, userId: string) => Promise<void>;
  deleteAllSessionsAndReset: (userId: string) => Promise<void>;
  ensureMainSession: (userId: string) => Promise<Session | null>;
}

export const useSessionStore = create<SessionStore>((set, get) => ({
  sessions: [],
  currentSessionId: null,
  loading: false,
  messages: [],
  _loadVersion: 0,

  setSessions: (sessions) => set({ sessions }),
  addSession: (session) =>
    set((state) => ({ sessions: [session, ...state.sessions] })),
  removeSession: (id) =>
    set((state) => ({
      sessions: state.sessions.filter((s) => s.id !== id),
      currentSessionId: state.currentSessionId === id ? null : state.currentSessionId,
      messages: state.currentSessionId === id ? [] : state.messages,
    })),
  setCurrentSessionId: (id) => {
    const oldId = get().currentSessionId;
    // 递增版本号，使所有正在飞行的旧请求作废
    const newVersion = get()._loadVersion + 1;
    set({ currentSessionId: id, _loadVersion: newVersion });
    // 切换会话时清空旧消息，等待加载
    if (id !== oldId) {
      set({ messages: [], loading: true });
      useChatStore.getState().clearMessages();
    }
  },
  setLoading: (loading) => set({ loading }),
  setMessages: (messages) => {
    set({ messages, loading: false });
    useChatStore.getState().setMessages(messages);
  },
  clearMessages: () => {
    set({ messages: [] });
    useChatStore.getState().clearMessages();
  },

  // ========== 服务端持久化操作 ==========

  /**
   * 从服务端加载会话列表
   */
  loadSessionsFromServer: async (userId: string) => {
    set({ loading: true });
    try {
      const sessions = await fetchSessions(userId);
      set({ sessions, loading: false });
    } catch {
      set({ loading: false });
    }
  },

  /**
   * 从服务端加载指定会话的消息历史 (首次加载，第1页)
   * 使用 _loadVersion 防止竞态条件：响应返回时如果版本号已变(用户切换到其他会话)则丢弃结果
   */
  loadMessagesFromServer: async (sessionId: string) => {
    const versionAtStart = get()._loadVersion;
    const chatStore = useChatStore.getState();
    chatStore.setIsLoadingHistory(true);
    chatStore.setHistoryPage(1);
    set({ loading: true });

    try {
      const resp = await fetchMessages(sessionId, PAGE_SIZE);
      // 竞态条件检查
      const currentState = get();
      if (
        currentState._loadVersion !== versionAtStart ||
        currentState.currentSessionId !== sessionId
      ) {
        console.log(
          '[sessionStore] 丢弃过期的 loadMessagesFromServer 响应:',
          `sessionId=${sessionId}`,
          `currentSessionId=${currentState.currentSessionId}`,
          `version=${versionAtStart}→${currentState._loadVersion}`
        );
        return;
      }

      const rawMessages = resp.messages || [];
      const msgs: Message[] = rawMessages.map((m, i: number) => {
        const raw = m as unknown as Record<string, unknown>;
        return {
          id: raw.id ? String(raw.id) : `hist_${i}_${Date.now()}`,
          role: (raw.role as Message['role']) || 'assistant',
          content: typeof raw.content === 'string' ? raw.content : '',
          timestamp: typeof raw.created_at === 'number' ? (raw.created_at as number) : Date.now(),
          isStreaming: false as const,
          msgType: (raw.msg_type as Message['msgType']) || undefined,
        };
      });

      set({ messages: msgs, loading: false });
      chatStore.setMessages(msgs);
      // 如果返回消息数量等于 PAGE_SIZE，说明可能还有更多
      chatStore.setHasMoreMessages(rawMessages.length >= PAGE_SIZE);
    } catch {
      const currentState = get();
      if (
        currentState._loadVersion !== versionAtStart ||
        currentState.currentSessionId !== sessionId
      ) {
        return;
      }
      set({ messages: [], loading: false });
      chatStore.clearMessages();
    } finally {
      useChatStore.getState().setIsLoadingHistory(false);
    }
  },

  /**
   * 加载更早的历史消息 (分页加载)
   */
  loadMoreMessagesFromServer: async (sessionId: string) => {
    const versionAtStart = get()._loadVersion;
    const chatStore = useChatStore.getState();

    if (chatStore.isLoadingHistory || !chatStore.hasMoreMessages) {
      return;
    }

    chatStore.setIsLoadingHistory(true);
    const nextPage = chatStore.historyPage + 1;

    try {
      const resp = await fetchMessages(sessionId, PAGE_SIZE);
      // 竞态条件检查
      const currentState = get();
      if (
        currentState._loadVersion !== versionAtStart ||
        currentState.currentSessionId !== sessionId
      ) {
        return;
      }

      const rawMessages = resp.messages || [];
      // 服务端返回的是最新的消息，我们需要取比当前消息更旧的部分
      // 由于后端当前不支持 offset/pagination，这里采用简单策略：
      // 如果返回的条数与当前消息数不同，说明有新消息，重新加载
      const currentMsgCount = chatStore.messages.length;

      if (rawMessages.length > currentMsgCount) {
        // 有新消息，取更早的
        const olderMessages: Message[] = rawMessages
          .slice(0, rawMessages.length - currentMsgCount)
          .map((m, i: number) => {
            const raw = m as unknown as Record<string, unknown>;
            return {
              id: raw.id ? String(raw.id) : `hist_old_${i}_${Date.now()}`,
              role: (raw.role as Message['role']) || 'assistant',
              content: typeof raw.content === 'string' ? raw.content : '',
              timestamp: typeof raw.created_at === 'number' ? (raw.created_at as number) : Date.now(),
              isStreaming: false as const,
            };
          });

        if (olderMessages.length > 0) {
          chatStore.prependMessages(olderMessages);
          chatStore.setHistoryPage(nextPage);
        }
        chatStore.setHasMoreMessages(olderMessages.length >= PAGE_SIZE);
      } else {
        chatStore.setHasMoreMessages(false);
      }

      set({ loading: false });
    } catch (err) {
      console.error('[sessionStore] 加载更多消息失败:', err);
    } finally {
      useChatStore.getState().setIsLoadingHistory(false);
    }
  },

  /**
   * 清空主对话的消息但保留会话本身
   */
  clearMainSessionMessages: async (sessionId: string) => {
    const ok = await apiClearMessages(sessionId);
    if (ok) {
      set({ messages: [] });
      useChatStore.getState().clearMessages();
    }
    return ok;
  },

  /**
   * 删除会话并自动切换到下一个可用会话
   */
  deleteSessionAndRefresh: async (id: string, userId: string) => {
    const ok = await apiDeleteSession(id);
    if (!ok) return;

    const state = get();
    const wasCurrent = state.currentSessionId === id;

    // 从服务端重新加载会话列表，保证侧边栏同步
    await get().loadSessionsFromServer(userId);
    const refreshed = get().sessions;

    if (wasCurrent) {
      if (refreshed.length > 0) {
        // 切换到列表中的第一个会话
        const nextId = refreshed[0].id;
        set({ currentSessionId: nextId });
        await get().loadMessagesFromServer(nextId);
      } else {
        // 没有会话了：管理员回到主对话，普通用户创建新对话
        set({ currentSessionId: null, messages: [] });
        useChatStore.getState().clearMessages();

        // 管理员：自动创建主对话
        if (isAdminUser(userId)) {
          const mainSession = await get().ensureMainSession(userId);
          if (mainSession) {
            set({ currentSessionId: mainSession.id });
            useChatStore.getState().clearMessages();
          }
        }
      }
    }
  },

  /**
   * 删除所有会话并重置状态
   */
  deleteAllSessionsAndReset: async (userId: string) => {
    const ok = await apiDeleteAllSessions(userId);
    if (!ok) return;

    // 从服务端重新加载会话列表
    await get().loadSessionsFromServer(userId);
    const refreshed = get().sessions;

    if (refreshed.length > 0) {
      // 服务端仍有会话（不应该发生，但做防御性处理）
      const latest = refreshed[0];
      set({ currentSessionId: latest.id, messages: [] });
      useChatStore.getState().clearMessages();
      await get().loadMessagesFromServer(latest.id);
      return;
    }

    // 所有会话已删除
    set({ sessions: [], currentSessionId: null, messages: [] });
    useChatStore.getState().clearMessages();

    // 管理员：自动创建主对话
    if (isAdminUser(userId)) {
      const mainSession = await get().ensureMainSession(userId);
      if (mainSession) {
        set({ currentSessionId: mainSession.id });
        useChatStore.getState().clearMessages();
      }
    }
  },

  /**
   * 确保主对话存在（管理员用户）。若不存在则创建并返回。
   */
  ensureMainSession: async (userId: string) => {
    const state = get();
    // 先检查本地列表
    const existing = state.sessions.find((s) => s.is_main);
    if (existing) return existing;

    // 本地没有，尝试从服务端加载
    await get().loadSessionsFromServer(userId);
    const refreshed = get().sessions.find((s) => s.is_main);
    if (refreshed) return refreshed;

    // 服务端也没有，创建主对话
    const sid = randomID();
    const created = await apiCreateSession(userId, sid, '主对话', true);
    if (created) {
      const newSession: Session = {
        id: created.id,
        user_id: created.user_id,
        title: created.title,
        is_main: created.is_main,
        created_at: String(created.created_at),
        updated_at: String(created.updated_at),
        message_count: 0,
      };
      set((s) => ({ sessions: [newSession, ...s.sessions] }));
      return newSession;
    }
    return null;
  },
}));
