import { User } from '@/types/user';
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import * as SecureStore from 'expo-secure-store';
import { Platform } from 'react-native';
interface AuthState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  task_id: string | null;
  url: string | null;
  refresh_token: string | null;
}

const initialState: AuthState = {
  user: null,
  token: null,
  isAuthenticated: false,
  task_id: null,
  url: null,
  refresh_token: null
};

export const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    setCredentials: (
      state,
      action: PayloadAction<{ user: User; token: string }>
    ) => {
      const { user, token } = action.payload;
      state.user = user;
      state.token = token;
      state.isAuthenticated = true;
    },
    clearCredentials: (state) => {
      state.user = null;
      state.token = null;
      state.isAuthenticated = false;
      if (Platform.OS === 'web') {
        localStorage.setItem('user', "");
        localStorage.setItem('token', "");
      } else {
        SecureStore.setItemAsync('user', "");
        SecureStore.setItemAsync('token', "");
      }
    },
    setGuestTaskData: (state, action: PayloadAction<{ task_id: string; url: string }>) => {
      state.task_id = action.payload.task_id;
      state.url = action.payload.url;
    }
  }
});

export const { setCredentials, clearCredentials, setGuestTaskData } = authSlice.actions;

export default authSlice.reducer;

// Selectors
export const selectCurrentUser = (state: { auth: AuthState }) => state.auth.user;
export const selectCurrentToken = (state: { auth: AuthState }) => state.auth.token;
export const selectIsAuthenticated = (state: { auth: AuthState }) => state.auth.isAuthenticated;
