import { create } from 'zustand';
import { authAPI } from '../services/api';

export const useAuthStore = create((set) => ({
  user: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null,
  token: localStorage.getItem('token') || null,
  isAuthenticated: !!localStorage.getItem('token'),
  loading: false,
  error: null,

  register: async (token, password) => {
    set({ loading: true, error: null });
    try {
      await authAPI.register({ token, password });
      set({ loading: false });
      return true;
    } catch (error) {
      set({ error: error.response?.data?.error || 'Registration failed', loading: false });
      return false;
    }
  },

  login: async (email, password) => {
    set({ loading: true, error: null });
    try {
      const response = await authAPI.login(email, password);
      localStorage.setItem('token', response.token);
      localStorage.setItem('user', JSON.stringify(response.user));
      set({
        user: response.user,
        token: response.token,
        isAuthenticated: true,
        loading: false,
      });
      return true;
    } catch (error) {
      set({ error: error.response?.data?.error || 'Login failed', loading: false });
      return false;
    }
  },

  requestSmsToken: async (roll_no, phone) => {
    set({ loading: true, error: null });
    try {
      await authAPI.requestSmsToken(roll_no, phone);
      set({ loading: false });
      return true;
    } catch (error) {
      set({ error: error.response?.data?.error || 'Failed to send token', loading: false });
      return false;
    }
  },

  loginWithSmsToken: async (roll_no, token) => {
    set({ loading: true, error: null });
    try {
      const response = await authAPI.verifySmsToken(roll_no, token);
      localStorage.setItem('token', response.token);
      localStorage.setItem('user', JSON.stringify(response.user));
      set({
        user: response.user,
        token: response.token,
        isAuthenticated: true,
        loading: false,
      });
      return true;
    } catch (error) {
      set({ error: error.response?.data?.error || 'Invalid token', loading: false });
      return false;
    }
  },

  logout: () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    set({
      user: null,
      token: null,
      isAuthenticated: false,
    });
  },

  updateProfile: async (data) => {
    set({ loading: true, error: null });
    try {
      await authAPI.updateProfile(data);
      const updatedUser = { ...useAuthStore.getState().user, ...data };
      localStorage.setItem('user', JSON.stringify(updatedUser));
      set({ user: updatedUser, loading: false });
      return true;
    } catch (error) {
      set({ error: error.response?.data?.error || 'Update failed', loading: false });
      return false;
    }
  },

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