import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import axios from 'axios';

const useAuthStore = create(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      isAuthenticated: false,
      loading: false,

      setUser: (user) => set({ user, isAuthenticated: !!user }),
      
      setToken: (token) => {
        set({ token });
        if (token) {
          axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
          localStorage.setItem('token', token);
        } else {
          delete axios.defaults.headers.common['Authorization'];
          localStorage.removeItem('token');
        }
      },

      login: async (credentials) => {
        try {
          set({ loading: true });
          const response = await axios.post('/api/login', credentials);
          const { user, token } = response.data;
          
          get().setToken(token);
          set({ user, isAuthenticated: true, loading: false });
          
          return { success: true };
        } catch (error) {
          set({ loading: false });
          return { 
            success: false, 
            error: error.response?.data?.message || 'Login failed' 
          };
        }
      },

      register: async (data) => {
        try {
          set({ loading: true });
          const response = await axios.post('/api/register', data);
          const { user, token } = response.data;
          
          get().setToken(token);
          set({ user, isAuthenticated: true, loading: false });
          
          return { success: true };
        } catch (error) {
          set({ loading: false });
          return { 
            success: false, 
            error: error.response?.data?.message || 'Registration failed' 
          };
        }
      },

      logout: async () => {
        try {
          await axios.post('/api/logout');
        } catch (error) {
          console.error('Logout error:', error);
        } finally {
          get().setToken(null);
          set({ user: null, isAuthenticated: false });
        }
      },

      fetchUser: async () => {
        try {
          const response = await axios.get('/api/me');
          set({ user: response.data.user, isAuthenticated: true });
        } catch (error) {
          get().logout();
        }
      },

      updateProfile: async (data) => {
        try {
          const response = await axios.put('/api/profile', data);
          set({ user: response.data.user });
          return { success: true, message: response.data.message };
        } catch (error) {
          return { 
            success: false, 
            error: error.response?.data?.message || 'Update failed' 
          };
        }
      },

      isSuperAdmin: () => {
        const { user } = get();
        return user?.roles?.some(role => role.name === 'Super Admin');
      },

      isCompanyAdmin: () => {
        const { user } = get();
        return user?.roles?.some(role => role.name === 'Company Admin');
      },

      canAccessCompany: (companyId) => {
        const { user } = get();
        return get().isSuperAdmin() || user?.company_id === companyId;
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        user: state.user,
        token: state.token,
        isAuthenticated: state.isAuthenticated,
      }),
    }
  )
);

export default useAuthStore;
