import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axiosInstance from '../../utils/axiosConfig';
import endpoints from '../../config/apiEndpoints';

// Define interfaces for the profile attributes
export interface ProfileAttribute {
  id: number;
  name: string;
  value?: string | number;
  height_range?: string;
  code?: string;
  flag?: string;
}

export interface ProfileAttributeGroup {
  [key: string]: ProfileAttribute[];
}

interface ProfileAttributeListState {
  attributes: ProfileAttributeGroup;
  loading: boolean;
  error: string | null;
}

const initialState: ProfileAttributeListState = {
  attributes: {},
  loading: false,
  error: null
};
const { profileAttributes: profileAttributesApi, statesGet: statesGetApi, citiesGet: citiesGetApi } = endpoints;

// Async thunk to fetch profile attributes
export const fetchProfileAttributes = createAsyncThunk(
  'profileAttributeList/fetchProfileAttributes',
  async (_, { rejectWithValue }) => {
    try {
      const response = await axiosInstance.get(profileAttributesApi);
      return response.data.data;
    } catch (error) {
      console.error('Error fetching profile attributes:', error);
      return rejectWithValue((error as Error).message);
    }
  }
);

// Async thunk to fetch districts/states by country ID
export const fetchStates = createAsyncThunk(
  'profileAttributeList/fetchStates',
  async (countryId: number, { rejectWithValue }) => {
    try {
      const url = statesGetApi.replace(':countryId', String(countryId));
      const response = await axiosInstance.get(url);
      return response.data.data;
    } catch (error) {
      console.error('Error fetching districts:', error);
      return rejectWithValue((error as Error).message);
    }
  }
);

// Async thunk to fetch upazilas/cities by state ID
export const fetchCities = createAsyncThunk(
  'profileAttributeList/fetchCities',
  async (stateId: string | number, { rejectWithValue }) => {
    try {
      const url = citiesGetApi.replace(':stateId', String(stateId));
      const response = await axiosInstance.get(url);
      return response.data.data;
    } catch (error) {
      console.error('Error fetching upazilas:', error);
      return rejectWithValue((error as Error).message);
    }
  }
);

const profileAttributeListSlice = createSlice({
  name: 'profileAttributeList',
  initialState,
  reducers: {
    clearAttributes: (state) => {
      state.attributes = {};
    }
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchProfileAttributes.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchProfileAttributes.fulfilled, (state, action: PayloadAction<ProfileAttributeGroup>) => {
        state.loading = false;
        state.attributes = action.payload;
      })
      .addCase(fetchProfileAttributes.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      .addCase(fetchStates.fulfilled, (state, action) => {
        state.attributes = {
          ...state.attributes,
          states: action.payload
        };
      })
      .addCase(fetchCities.fulfilled, (state, action) => {
        state.attributes = {
          ...state.attributes,
          cities: action.payload
        };
      });
  }
});

export const { clearAttributes } = profileAttributeListSlice.actions;
export default profileAttributeListSlice.reducer;