import { create } from 'zustand';
import * as authService from '../services/authService';
import { setUser as setCrashlyticsUser } from '../services/crashlytics';
import { setAnalyticsUser, trackSignUp, trackLogin } from '../services/analytics';

const useAuthStore = create((set) => ({
  session: null,
  user: null,
  loading: false,
  error: null,

  setSession: (session) => {
    const user = session?.user ?? null;
    if (user) {
      setCrashlyticsUser(user.id, user.email);
      setAnalyticsUser(user.id);
    }
    set({ session, user, loading: false, error: null });
  },

  login: async (email, password) => {
    set({ loading: true, error: null });
    try {
      const data = await authService.signIn(email, password);
      trackLogin('email');
      set({ session: data.session, user: data.user, loading: false });
      return data;
    } catch (e) {
      set({ loading: false, error: e.message });
      throw e;
    }
  },

  loginAsDemo: async () => {
    set({ loading: true, error: null });
    try {
      const data = await authService.signInAsDemo();
      trackLogin('demo');
      set({ session: data.session, user: data.user, loading: false });
      return data;
    } catch (e) {
      set({ loading: false, error: e.message });
      throw e;
    }
  },

  loginWithGoogle: async () => {
    set({ loading: true, error: null });
    try {
      const data = await authService.signInWithGoogle();
      set({ loading: false });
      return data;
    } catch (e) {
      set({ loading: false, error: e.message });
      throw e;
    }
  },

  register: async (email, password) => {
    set({ loading: true, error: null });
    try {
      const data = await authService.signUp(email, password);
      trackSignUp('email');
      // If signup returned a session (offline mode or auto-confirm), set it
      if (data?.session) {
        set({
          session: data.session,
          user: data.session?.user ?? data.user ?? null,
          loading: false,
        });
      } else {
        set({ loading: false });
      }
      return data;
    } catch (e) {
      set({ loading: false, error: e.message });
      throw e;
    }
  },

  registerWithPhone: async (phone, password) => {
    set({ loading: true, error: null });
    try {
      const data = await authService.signUpWithPhone(phone, password);
      set({ loading: false });
      return data;
    } catch (e) {
      set({ loading: false, error: e.message });
      throw e;
    }
  },

  verifyOtp: async (identifier, code, method) => {
    set({ loading: true, error: null });
    try {
      const data = await authService.verifyOtp(identifier, code, method);
      if (data?.session) {
        const user = data.session?.user ?? data.user ?? null;
        if (user) setCrashlyticsUser(user.id, user.email || identifier);
        set({ session: data.session, user, loading: false });
      } else {
        set({ loading: false });
      }
      return data;
    } catch (e) {
      set({ loading: false, error: e.message });
      throw e;
    }
  },

  logout: async () => {
    try {
      await authService.signOut();
    } catch (_) {
      // proceed even if signOut fails (e.g. network)
    }
    set({ session: null, user: null, error: null });
  },

  fetchSession: async () => {
    try {
      const session = await authService.getSession();
      set({ session, user: session?.user ?? null });
      return session;
    } catch (_) {
      set({ session: null, user: null });
      return null;
    }
  },

  resetPassword: async (email, newPassword) => {
    set({ loading: true, error: null });
    try {
      const result = await authService.resetPassword(email, newPassword);
      set({ loading: false });
      return result;
    } catch (e) {
      set({ loading: false, error: e.message });
      throw e;
    }
  },

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

export default useAuthStore;
