import { create } from 'zustand';
import {
  clearStoredSession,
  getStoredSession,
  setStoredSession,
} from '@/lib/auth/tokenManager';
import {
  getCurrentSession,
  login as loginRequest,
  logout as logoutRequest,
  register as registerRequest,
  type SessionInfo,
  type User,
} from '@/lib/api/auth';

interface AuthState {
  user: User | null;
  session: SessionInfo | null;
  accessToken: string | null;
  refreshToken: string | null;
  expiresAt: number | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  error: string | null;
  hasHydrated: boolean;
  status: 'idle' | 'authenticated' | 'anonymous';
  setAuth: (user: User, session: { accessToken: string; refreshToken?: string | null; expiresAt?: number | null }) => void;
  logout: () => Promise<void>;
  login: (credentials: { username: string; password: string }) => Promise<void>;
  register: (data: { username: string; email: string; password: string }) => Promise<void>;
  clearError: () => void;
  fetchSession: () => Promise<void>;
  updateAvatar: (avatarUrl: string) => void;
  hydrate: () => void;
}

export const useAuthStore = create<AuthState>((set, get) => ({
  user: null,
  session: null,
  accessToken: null,
  refreshToken: null,
  expiresAt: null,
  isAuthenticated: false,
  isLoading: false,
  error: null,
  hasHydrated: false, // 初始为 false，等待 hydration 完成
  status: 'idle',

  setAuth: (user, session) => {
    const storedSession = {
      accessToken: session.accessToken,
      refreshToken: session.refreshToken ?? null,
      expiresAt: session.expiresAt ?? null,
    };
    setStoredSession(storedSession);
    set({
      user,
      session: null,
      accessToken: storedSession.accessToken,
      refreshToken: storedSession.refreshToken,
      expiresAt: storedSession.expiresAt,
      isAuthenticated: true,
      status: 'authenticated',
    });
  },

  logout: async () => {
    const session = getStoredSession();
    const refreshToken = session.refreshToken;
    const accessToken = session.accessToken;

    try {
      if (accessToken) {
        await logoutRequest(refreshToken ?? undefined);
      }
    } catch {
      // Clear local auth state even if server-side revocation fails.
    } finally {
      clearStoredSession();
      set({
        user: null,
        session: null,
        accessToken: null,
        refreshToken: null,
        expiresAt: null,
        isAuthenticated: false,
        isLoading: false,
        error: null,
        status: 'anonymous',
      });
    }
  },

  login: async (credentials: { username: string; password: string }) => {
    set({ isLoading: true, error: null });
    try {
      const { accessToken, refreshToken, expiresIn, user } = await loginRequest(credentials);
      if (!accessToken) {
        throw new Error('No access token received');
      }
      const expiresAt = Date.now() + expiresIn * 1000;
      setStoredSession({ accessToken, refreshToken, expiresAt });
      set({
        user,
        session: null,
        accessToken,
        refreshToken,
        expiresAt,
        isAuthenticated: true,
        isLoading: false,
        status: 'authenticated',
      });
    } catch (err: any) {
      set({ error: err.response?.data?.message || err.message || 'Login failed', isLoading: false });
      throw err;
    }
  },

  register: async (data: { username: string; email: string; password: string }) => {
    set({ isLoading: true, error: null });
    try {
      const { accessToken, refreshToken, expiresIn, user } = await registerRequest(data);
      if (!accessToken) {
        throw new Error('No access token received');
      }
      const expiresAt = Date.now() + expiresIn * 1000;
      setStoredSession({ accessToken, refreshToken, expiresAt });
      set({
        user,
        session: null,
        accessToken,
        refreshToken,
        expiresAt,
        isAuthenticated: true,
        isLoading: false,
        status: 'authenticated',
      });
    } catch (err: any) {
      set({ error: err.response?.data?.message || 'Registration failed', isLoading: false });
      throw err;
    }
  },

  clearError: () => set({ error: null }),

  fetchSession: async () => {
    try {
      const response = await getCurrentSession();
      set((state) => ({
        user: response.user,
        session: response.session ?? null,
        accessToken: state.accessToken,
        refreshToken: state.refreshToken,
        expiresAt: response.session?.expiresAt ?? state.expiresAt,
        isAuthenticated: response.authenticated,
        status: response.authenticated ? 'authenticated' : 'anonymous',
      }));
    } catch {
      await get().logout();
    }
  },

  updateAvatar: (avatarUrl: string) => {
    set((state) => ({
      user: state.user ? { ...state.user, avatarUrl } : null,
    }));
  },

  hydrate: () => {
    const session = getStoredSession();
    if (session.accessToken) {
      // Token 存在，设置认证状态
      set({
        session: null,
        accessToken: session.accessToken,
        refreshToken: session.refreshToken,
        expiresAt: session.expiresAt,
        isAuthenticated: true,
        status: 'authenticated',
      });
      // 异步获取用户信息
      get().fetchSession();
    } else {
      set({ status: 'anonymous', session: null });
    }
    // 标记 hydration 完成
    set({ hasHydrated: true });
  },
}));
