// followUpSlice.ts
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { getAllTodayFollowUpLeads } from './service';

export const fetchAllTodayFollowUpLeads = createAsyncThunk('followUpLeads/fetchAllTodayFollowUpLeads', async(tabKey: string) => {
    const leads = await getAllTodayFollowUpLeads(tabKey);
    return leads;
  }
);

interface FollowUpState {
    allTodayFollowUpLeads: any[]
    status: 'loading' | 'succeeded' | 'failed'
    error: string | null
    listLoading: boolean
  }

  const initialState: FollowUpState = {
    allTodayFollowUpLeads: [],
    status: 'loading',
    error: null,
    listLoading: true,

  };
const followUpSlice = createSlice({
  name: 'followUpLeads',
  initialState,
  reducers: {
    // reducer function to remove a lead by its id from allTodayFollowUpLeads array.
    removeTodayFollowUpLead(state, action) {
      const leadIdToRemove = action.payload;
      if (!Array.isArray(state.allTodayFollowUpLeads)) {
        state.allTodayFollowUpLeads = [];
      }
      state.allTodayFollowUpLeads = state.allTodayFollowUpLeads.filter((lead) => lead.id !== leadIdToRemove);
    },
    // reducer function to Add a lead object into the allTodayFollowUpLeads array.
    addTodayFollowUpLead(state, action) {
      const newLead = action.payload;
      if (!Array.isArray(state.allTodayFollowUpLeads)) {
        state.allTodayFollowUpLeads = [];
      }
      const existingLead = state.allTodayFollowUpLeads.find((lead) => lead.id === newLead.id);
      if (existingLead) {
        existingLead.follow_up_date = newLead.follow_up_date;
        existingLead.tag = newLead.tag;
        existingLead.configuration = newLead.configuration;
      } else {
        state.allTodayFollowUpLeads.push(newLead);
      }
    },
},
  extraReducers: (builder) => {
        builder
          .addCase(fetchAllTodayFollowUpLeads.pending, (state) => {
            state.status = 'loading';
            state.listLoading = true;
          })
          .addCase(fetchAllTodayFollowUpLeads.fulfilled, (state: any, action: any) => {
            state.status = 'succeeded';
            state.listLoading = false;
            state.allTodayFollowUpLeads = action.payload?.data;
          })
          .addCase(fetchAllTodayFollowUpLeads.rejected, (state: any, action: any) => {
            state.status = 'failed';
            state.listLoading = false;
            state.error = action.error.message;
          })
  },
});

export const { removeTodayFollowUpLead, addTodayFollowUpLead  } = followUpSlice.actions;
export default followUpSlice.reducer;
