import { useCallback, useEffect, useRef } from 'react';
import { useSessionStore, isAdminUser } from '@/store/sessionStore';
import { useChatStore } from '@/store/chatStore';
import { createSession as apiCreateSession } from '@/api/sessions';
import type { Session } from '@/types/session';

const SESSION_HASH_PREFIX = 'session=';

function setHashSessionId(sessionId: string | null) {
  if (sessionId) {
    window.location.hash = SESSION_HASH_PREFIX + sessionId;
  } else {
    history.replaceState(null, '', window.location.pathname + window.location.search);
  }
}

/** 生成简易随机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}`;
}

/** 获取当前用户ID */
function getUserId(): string {
  return localStorage.getItem('user_id') || '';
}

export function useSession() {
  const {
    sessions,
    currentSessionId,
    loading,
    setSessions,
    addSession,
    removeSession,
    setCurrentSessionId,
    setLoading,
    loadSessionsFromServer,
    loadMessagesFromServer,
    clearMainSessionMessages,
    deleteSessionAndRefresh,
    deleteAllSessionsAndReset,
    ensureMainSession,
  } = useSessionStore();

  const userId = getUserId();
  const isAdmin = isAdminUser(userId);

  /** 从服务端加载会话列表 */
  const loadSessions = useCallback(async () => {
    if (!userId) return;
    await loadSessionsFromServer(userId);
  }, [userId, loadSessionsFromServer]);

  // 初始加载
  useEffect(() => {
    loadSessions();
  }, [loadSessions]);

  /** 创建新会话 (isMain 默认为 false) */
  const createSession = useCallback(
    async (title?: string, isMain: boolean = false) => {
      const sid = randomID();
      const created = await apiCreateSession(
        userId,
        sid,
        title || '新的对话',
        isMain
      );
      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,
        };
        addSession(newSession);
        setCurrentSessionId(newSession.id);
        setHashSessionId(newSession.id);
        return newSession;
      }
      return null;
    },
    [userId, addSession, setCurrentSessionId]
  );

  /** 清空主对话消息 */
  const clearMainSession = useCallback(async () => {
    const mainSession = useSessionStore
      .getState()
      .sessions.find((s: Session) => s.is_main);
    if (!mainSession) {
      // 尝试确保主对话存在
      const ensured = await ensureMainSession(userId);
      if (!ensured) return false;
      return clearMainSessionMessages(ensured.id);
    }
    return clearMainSessionMessages(mainSession.id);
  }, [userId, clearMainSessionMessages, ensureMainSession]);

  /** 删除单个会话 */
  const deleteSession = useCallback(
    async (id: string) => {
      await deleteSessionAndRefresh(id, userId);
    },
    [userId, deleteSessionAndRefresh]
  );

  /** 删除所有会话 */
  const deleteAllSessions = useCallback(async () => {
    await deleteAllSessionsAndReset(userId);
  }, [userId, deleteAllSessionsAndReset]);

  /** 切换当前会话 */
  const setCurrentSession = useCallback(
    async (id: string) => {
      setCurrentSessionId(id);
      setHashSessionId(id);
      // 加载该会话的消息历史
      await loadMessagesFromServer(id);
    },
    [setCurrentSessionId, loadMessagesFromServer]
  );

  return {
    sessions,
    currentSessionId,
    loading,
    isAdmin,
    userId,
    loadSessions,
    createSession,
    clearMainSession,
    deleteSession,
    deleteAllSessions,
    setCurrentSession,
  };
}
