import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import * as api from "../api";
import { toast } from "react-toastify"; // Import toast here
import axios from "axios";

export const submitFundDetails = createAsyncThunk(
  "fundDetails/submit",
  async ({ fundDetails,id,navigate }, { rejectWithValue }) => {
    try {
      const response = await api.submitFundDetails(fundDetails, id);
      toast.success("Details submitted successfully"); // Show toast on success
      navigate(`/property/${id}`); // Navigate after successful submission
      return response.data; // Assuming you return JSON data
    } catch (error) {
      toast.error("Failed to submit details"); // Show error toast
      return rejectWithValue(error.response.data);
    }
  }
);


export const getFundDetailsById = createAsyncThunk(
    "fundDetails/getFundDetailsById",
    async (id, { rejectWithValue }) => {
      try {
        const response = await axios.get(`http://localhost:3002/fundDetails/${id}`);
        return response.data;
      } catch (error) {
        return rejectWithValue(error.response.data);
      }
    }
  );


const fundDetailsSlice = createSlice({
  name: "fundDetails",
  initialState: {
    fundDetails: null,
    status: null,
    error: null,
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
    .addCase(getFundDetailsById.pending, (state) => {
      state.status = "loading";
    })
    .addCase(getFundDetailsById.fulfilled, (state, action) => {
      state.status = "succeeded";
      state.fundDetails = action.payload;
    })
    .addCase(getFundDetailsById.rejected, (state, action) => {
      state.status = "failed";
      state.error = action.payload;
    })
    .addCase(submitFundDetails.fulfilled, (state, action) => {
      state.fundDetails = action.payload;
    })
    .addCase(submitFundDetails.rejected, (state, action) => {
      state.error = action.payload;
    });
},
});

export default fundDetailsSlice.reducer;