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

interface State {
  id: string;
  nom: string;
  createdBy: string;
  description: string;
}

interface StatesState {
  states: State[];
  loading: boolean;
  error: string | null;
}

const initialState: StatesState = {
  states: [],
  loading: false,
  error: null,
};

export const fetchStates = createAsyncThunk(
  'states/fetchStates',
  async (_, { rejectWithValue }) => {
    try {
      console.log('Fetching states from Redux thunk...');
      const response = await axios.get('http://localhost:8000/api/states', {
        headers: {
          'Accept': 'application/json',
        },
      });
      console.log('States fetched successfully:', response.data);
      return response.data;
    } catch (error) {
      console.error('Error in fetchStates 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 states');
    }
  }
);

const statesSlice = createSlice({
  name: 'states',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchStates.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchStates.fulfilled, (state, action) => {
        state.loading = false;
        state.states = action.payload;
      })
      .addCase(fetchStates.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || 'Failed to fetch states';
      });
  },
});

export default statesSlice.reducer; 