import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

interface Group {
  id: string;
  name: string;
  description: string;
}

interface GroupsState {
  groups: Group[];
  loading: boolean;
  error: string | null;
}

const initialState: GroupsState = {
  groups: [],
  loading: false,
  error: null,
};

export const fetchGroups = createAsyncThunk(
  'groups/fetchGroups',
  async (_, { rejectWithValue }) => {
    try {
      console.log('Fetching groups from Redux thunk...');
      const response = await axios.get('http://127.0.0.1:8000/api/groups/', {
        headers: {
          'Accept': 'application/json',
        },
      });
      console.log('Groups fetched successfully:', response.data);
      return response.data;
    } catch (error) {
      console.error('Error in fetchGroups thunk:', error);
      if (axios.isAxiosError(error)) {
        const errorMessage = error.response?.data?.error || error.response?.data?.details || error.message;
        return rejectWithValue(errorMessage);
      }
      return rejectWithValue('An unexpected error occurred while fetching groups');
    }
  }
);

const groupsSlice = createSlice({
  name: 'groups',
  initialState,
  reducers: {
    clearGroupsError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchGroups.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchGroups.fulfilled, (state, action) => {
        state.loading = false;
        state.groups = action.payload;
        state.error = null;
      })
      .addCase(fetchGroups.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string || 'Failed to fetch groups';
      });
  },
});

export const { clearGroupsError } = groupsSlice.actions;
export default groupsSlice.reducer; 