import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import * as api from "../api";
import axios from "axios";

const BASE_URL = import.meta.env.VITE_REACT_APP_SECRET; 



export const login = createAsyncThunk(
  "auth/login",
  async ({ formValue, navigate }, { rejectWithValue }) => {
    try {
      const response = await api.signIn(formValue);
      navigate("/dashboard");
      return response.data;
    } catch (err) {
      return rejectWithValue(err.response.data);
    }
  }
);

export const register = createAsyncThunk(
  "auth/register",
  async ({ formValue, navigate, toast }, { rejectWithValue }) => {
    try {
      const response = await api.signUp(formValue);
      console.log("response", response)
      toast.success("Register Successfully");
      navigate("/registrationsuccess");
      return response.data;
    } catch (err) {
      return rejectWithValue(err.response.data);
    }
  }
);



// Thunk to update user details
export const updateUser = createAsyncThunk(
  'auth/updateUser',
  async ({formData, toast, navigate},  { rejectWithValue }) => {
    try {
      const response = await axios.put(`${BASE_URL}/users/update`, formData);
      // console.log('Update user response:', response.data);
      toast.success("Updated Successfully");
      navigate("/login");
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

export const WillingToInvest = createAsyncThunk(
  "auth/WillingToInvest",
  async ({formData, toast }, { rejectWithValue }) => {
    try {
      const response = await api.investFunds(formData); // Call the backend API
      toast.success("Investment amount updated successfully!");
      return response.data;
    } catch (error) {
      toast.error(error.response.data.message);
      return rejectWithValue(error.response.data);
    }
  }
);


const authSlice = createSlice({
  name: "auth",
  initialState: {
    user: null,
    error: "",
    loading: false,
    isLoading: false,
  },
  reducers: {
    setUser: (state, action) => {
      state.user = action.payload;
    },
    setLogout: (state) => {
      localStorage.clear();
      state.user = null;
    },
    setUserDetails: (state, action) => {
      state.user = action.payload;
    },
    updateUser: (state, action) => {
      const updatedUser = action.payload;
      state.user = { ...state.user, ...updatedUser }; // Update user state without removing it
  },
  },
  extraReducers: (builder) => {
    builder
      .addCase(login.pending, (state) => {
        state.loading = true;
      })
      .addCase(login.fulfilled, (state, action) => {
        state.loading = false;
        localStorage.setItem("profile", JSON.stringify({ ...action.payload }));
        state.user = action.payload;
      })
      .addCase(login.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload.message;
      })
      .addCase(register.pending, (state) => {
        state.loading = true;
      })
      .addCase(register.fulfilled, (state, action) => {
        state.loading = false;
        localStorage.setItem("profile", JSON.stringify({ ...action.payload }));
        state.user = action.payload;
      })
      .addCase(register.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload.message;
      })
      .addCase(updateUser.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(updateUser.fulfilled, (state, action) => {
        state.isLoading = false;
        state.user = action.payload; // Update the user state with the new data
      })
      .addCase(updateUser.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload;
      })

      .addCase(WillingToInvest.pending, (state) => {
        state.loading = true;
      })
      .addCase(WillingToInvest.fulfilled, (state, action) => {
        state.loading = false;
        state.user = { ...state.user, result: action.payload }; // Update the user result with the new data
      })
      .addCase(WillingToInvest.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      
      
      ;
  },
});

export const { setUser, setLogout, setUserDetails } = authSlice.actions;

export default authSlice.reducer;
