import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  user: JSON.parse(localStorage.getItem('user')) || null,
  userData: JSON.parse(localStorage.getItem('userData')) || null,
  apiKey: localStorage.getItem('apiKey') || null,
  isAdmin: localStorage.getItem('isAdmin') === 'true',
  isAuthenticated: !!localStorage.getItem('apiKey'),
  loading: false,
  error: null,
};

export const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    loginStart: (state) => {
      state.loading = true;
      state.error = null;
    },
    loginSuccess: (state, action) => {
      state.loading = false;
      state.isAuthenticated = true;
      state.user = action.payload.user;
      state.userData = {
        id: action.payload.user, 
        apiKey: action.payload.apiKey, 
        email: action.payload.email,
        firstName: action.payload.firstName,
        lastName: action.payload.lastName,
        isAdmin: action.payload.isAdmin
      };
      state.apiKey = action.payload.apiKey;
      state.isAdmin = action.payload.isAdmin;
      localStorage.setItem('apiKey', action.payload.apiKey);
      localStorage.setItem('isAdmin', action.payload.isAdmin);
      localStorage.setItem('user', JSON.stringify(action.payload.user));
      localStorage.setItem('userData', JSON.stringify({
        id: action.payload.user, 
        apiKey: action.payload.apiKey, 
        isAdmin: action.payload.isAdmin
      }));
    },
    loginFailed: (state, action) => {
      state.loading = false;
      state.error = action.payload;
    },
    logout: (state) => {
      state.isAuthenticated = false;
      state.user = null;
      state.userData = null;
      state.apiKey = null;
      state.isAdmin = false;
      localStorage.removeItem('apiKey');
      localStorage.removeItem('isAdmin');
      localStorage.removeItem('user');
      localStorage.removeItem('userData');
    },
    clearError: (state) => {
      state.error = null;
    },
  },
});

export const { loginStart, loginSuccess, loginFailed, logout, clearError } = authSlice.actions;

// Selectors
export const selectIsAuthenticated = (state) => state.auth.isAuthenticated;
export const selectIsAdmin = (state) => state.auth.isAdmin;
export const selectCurrentUser = (state) => state.auth.user;
export const selectApiKey = (state) => state.auth.apiKey;
export const selectAuthLoading = (state) => state.auth.loading;
export const selectAuthError = (state) => state.auth.error;

export default authSlice.reducer;