import { create } from 'zustand';
import * as authApi from '@/lib/api/auth';
import { getQueryClient } from '@/lib/query/query-client';
import { trackEvent, resetAnalytics, AnalyticsEvents } from '@/lib/analytics';
import type { UserResponse } from '@/lib/api/auth';

interface AuthState {
  user: UserResponse | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  error: string | null;

  login: (credentials: { username: string; password: string }) => Promise<void>;
  register: (data: {
    username: string;
    email: string;
    password: string;
    first_name: string;
    last_name: string;
  }) => Promise<void>;
  logout: () => Promise<void>;
  fetchUser: () => Promise<void>;
  clearError: () => void;
}

export const useAuthStore = create<AuthState>()((set) => ({
  user: null,
  isAuthenticated: false,
  isLoading: false,
  error: null,

  login: async (credentials) => {
    set({ isLoading: true, error: null });
    try {
      const response = await authApi.login(credentials);
      trackEvent(AnalyticsEvents.USER_SIGNED_IN, { method: 'email', platform: 'web' });
      set({ user: response.user, isAuthenticated: true, isLoading: false });
      window.location.href = '/app';
    } catch (err) {
      const message =
        err instanceof Error ? err.message : 'Login failed. Please try again.';
      set({ isLoading: false, error: message });
    }
  },

  register: async (data) => {
    set({ isLoading: true, error: null });
    try {
      await authApi.register(data);
      trackEvent(AnalyticsEvents.USER_REGISTERED, { method: 'email', platform: 'web' });
      set({ isLoading: false });
    } catch (err) {
      const message =
        err instanceof Error
          ? err.message
          : 'Registration failed. Please try again.';
      set({ isLoading: false, error: message });
      throw err;
    }
  },

  logout: async () => {
    set({ isLoading: true, error: null });
    try {
      await authApi.logout();
    } catch {
      // Even if logout fails server-side, clear local state
    } finally {
      // Clear React Query cache to prevent stale data leaking into demo mode
      getQueryClient().clear();
      resetAnalytics();
      set({
        user: null,
        isAuthenticated: false,
        isLoading: false,
        error: null,
      });
      window.location.href = '/login';
    }
  },

  fetchUser: async () => {
    set({ isLoading: true, error: null });
    try {
      const user = await authApi.getCurrentUser();
      set({ user, isAuthenticated: true, isLoading: false });
    } catch {
      set({ user: null, isAuthenticated: false, isLoading: false });
    }
  },

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