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

export const submitProperty = createAsyncThunk(
  "property/submitProperty",
  async (propertyData, { rejectWithValue }) => {
    try {
      const response = await api.submitProperty(propertyData);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

// Action to fetch user properties without pagination
// export const fetchUserProperties = createAsyncThunk(
//   "property/fetchUserProperties",
//   async (userId, { rejectWithValue }) => {
//     try {
//       const response = await api.fetchUserProperties(userId);
//       return response.data;
//     } catch (error) {
//       return rejectWithValue(error.response.data);
//     }
//   }
// );

// Action to fetch user properties with pagination
export const fetchUserProperties = createAsyncThunk(
  "property/fetchUserProperties",
  async ({ userId, page, limit }, { rejectWithValue }) => {
    try {
      const response = await api.fetchUserProperties(userId, page, limit);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

export const fetchPropertyById = createAsyncThunk(
  "property/fetchPropertyById",
  async (id, { rejectWithValue }) => {
    try {
      const response = await api.fetchPropertyById(id);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

export const updateProperty = createAsyncThunk(
  "property/updateProperty",
  async ({ id, propertyData }, { rejectWithValue }) => {
    try {
      const response = await api.updateProperty(id, propertyData);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

// export const getProperties = createAsyncThunk("property/getProperties", async () => {
//   const response = await axios.get(`${import.meta.env.VITE_REACT_APP_SECRET}/properties`); // Backend endpoint
//   return response.data;
// });

// export const getProperties = createAsyncThunk(
//   'properties/getProperties',
//   async ({ page, limit, keyword = "" }) => {
//     const response = await axios.get(`${import.meta.env.VITE_REACT_APP_SECRET}/properties?page=${page}&limit=${limit}&keyword=${keyword}`);
//     return response.data;
//   }
// );

export const getProperties = createAsyncThunk(
  'properties/getProperties',
  async ({ page, limit, keyword = "" }) => {
    const response = await axios.get(`${import.meta.env.VITE_REACT_APP_SECRET}/properties?page=${page}&limit=${limit}&keyword=${keyword}`);
    return response.data;
  }
);


const propertySlice = createSlice({
  name: "property",
  initialState: {
    property: {},
    status: "idle",
    error: null,
    userProperties: [],
    selectedProperty: null,
    totalPages: 0,
    currentPage: 1,
    loading: false,
    properties: [],
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(submitProperty.pending, (state) => {
        state.status = "loading";
      })
      .addCase(submitProperty.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.property = action.payload;
      })
      .addCase(submitProperty.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
      })

      .addCase(fetchUserProperties.pending, (state) => {
        state.loading = true;
      })
      .addCase(fetchUserProperties.fulfilled, (state, { payload }) => {
        state.loading = false;
        state.userProperties = payload.properties;
        state.totalPages = payload.totalPages;
        state.currentPage = payload.currentPage;
      })
      .addCase(fetchUserProperties.rejected, (state, { payload }) => {
        state.loading = false;
        state.error = payload;
      })

      .addCase(fetchPropertyById.pending, (state) => {
        state.status = "loading";
      })
      .addCase(fetchPropertyById.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.selectedProperty = action.payload;
      })
      .addCase(fetchPropertyById.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
      })
      .addCase(updateProperty.pending, (state) => {
        state.status = "loading";
      })
      .addCase(updateProperty.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.selectedProperty = action.payload;
      })
      .addCase(updateProperty.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
      })

      .addCase(getProperties.pending, (state) => {
        state.loading = true;
      })
      .addCase(getProperties.fulfilled, (state, action) => {
        state.loading = false;
        state.properties = action.payload.data;
        state.totalPages = action.payload.totalPages;
        state.currentPage = action.payload.currentPage;
      })
      .addCase(getProperties.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message;
      })
      ;
  },
});

export default propertySlice.reducer;
