import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import endpoints from "../../config/apiEndpoints";
import axiosInstance from "../../utils/axiosConfig";

interface Profile {
  first_name: string | null;
  last_name: string | null;
  age: string | number | null;
  photo: string | null;
  photo_status: string | null;
  cover_photo: string | null;
  cover_status: string | null;
  gallery_image_1: string | null;
  gallery_image_1_status: string | null;
  gallery_image_2: string | null;
  gallery_image_2_status: string | null;
  profile_visit: string | number | null;
  posts: string | number | null;
  visits: string | number | null;
  followers: string | number | null;
  following: string | number | null;
  is_follow: number | null;
  onbehalf: string | null;
  last_login: string | null;
  is_interested: number | null;
  tagline: string | null;
  profession: string | null;
  profession_histories: [] | null;
  income_monthly: string | null;
  highest_education: string | null;
  education_histories: [] | null;
  mother_tongue: string | null;
  current_location: string | null;
  citizenship_country: string | null;
  hometown: string | null;
  gender: string | null;
  height: string | null;
  weight: string | null;
  marital_status: string | null;
  smoking: string | null;
  drinking: string | null;
  blood_group: string | null;
  diet: string | null;
  children: string | null;
  religion: string | null;
  caste: string | null;
  sub_caste: string | null;
}
export interface FeedPost {
  picture_type: string;
  id: number;
  package_update_alert: boolean;
  user_id: number;
  gender: string;
  user_photo: string;
  image: string;
  image_id: number;
  post_id: number;
  description: string | null;
  audio_file_path: string | null;
  like: number;
  love: number | null;
  care: number | null;
  laugh: number | null;
  angry: number | null;
  sad: number | null;
  wow: number | null;
  is_follow: string | null;
  total_react: number;
  reaction_user: number | string | null;
  provide_react: string | null;
  name: string;
  created_at: string;
  content?: string;
  time?: string;
}

interface ProfileState {
  profileData: Profile;
  feedPosts: FeedPost[];
  postPagination: {
      current_page: number;
      from: number;
      last_page: number;
      per_page: number;
      to: number;
      total: number;
    } | null;
  loading: boolean;
  error: string | null;
  dataFetched: boolean;
  postDataFetched: boolean;
}

const initialProfile: Profile = {
  first_name: null,
  last_name: null,
  age: null,
  photo: null,
  photo_status: null,
  cover_photo: null,
  cover_status: null,
  gallery_image_1: null,
  gallery_image_1_status: null,
  gallery_image_2: null,
  gallery_image_2_status: null,
  profile_visit: null,
  posts: null,
  visits: null,
  followers: null,
  following: null,
  is_follow: null,
  onbehalf: null,
  last_login: null,
  is_interested: null,
  tagline: null,
  profession: null,
  profession_histories: [],
  income_monthly: null,
  highest_education: null,
  education_histories: [],
  mother_tongue: null,
  current_location: null,
  citizenship_country: null,
  hometown: null,
  gender: null,
  height: null,
  weight: null,
  marital_status: null,
  smoking: null,
  drinking: null,
  blood_group: null,
  diet: null,
  children: null,
  religion: null,
  caste: null,
  sub_caste: null
};

const initialState: ProfileState = {
  profileData: initialProfile,
  feedPosts: [],
  postPagination: null,
  loading: false,
  error: null,
  dataFetched: false,
  postDataFetched: false,
};

const { profileInfo: profileInfoApi, memberFeed: memberFeedApi } = endpoints;

export const fetchProfileData = createAsyncThunk(
  'profile/fetchData',
  async (id: string | number, { rejectWithValue }) => {
    try {
      const url = profileInfoApi.replace(':id', String(id));
      const response = await axiosInstance.get(url);
      return response.data?.data;
    } catch (error) {
      console.error('Error fetching messages data:', error);
      return rejectWithValue((error as Error).message);
    }
  }
);  
export const fetchMemberFeed = createAsyncThunk(
  'memberFeed/fetchData',
  async ({ page = 1, id }: { page?: number; id: string | number }, { rejectWithValue }) => {
    try {
      const url = memberFeedApi.replace(':id', String(id));
      const response = await axiosInstance.get(url+'?page='+page);
      console.log(response.data);
      return response.data;
    } catch (error) {
      console.error('Error fetching messages data:', error);
      return rejectWithValue((error as Error).message);
    }
  }
);  

const profileSlice = createSlice({
  name: 'profile',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchProfileData.pending, (state) => {
        state.loading = true;
        state.error = null;
        state.dataFetched = false;
      })
      .addCase(fetchProfileData.fulfilled, (state, action) => {
        state.loading = false;
        state.profileData = action.payload;
        state.dataFetched = true;
      })
      .addCase(fetchProfileData.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      .addCase(fetchMemberFeed.pending, (state) => {
        state.loading = true;
        state.error = null;
        state.postDataFetched = false;
      })
      .addCase(fetchMemberFeed.fulfilled, (state, action) => {
        state.loading = false;
        
        const { current_page, from, last_page, per_page, to, total } = action.payload?.meta || {};
        
        // Update post pagination
        state.postPagination = {
          current_page,
          from,
          last_page,
          per_page,
          to,
          total
        };
        
        // Check if we're appending or replacing posts
        if (current_page === 1) {
          state.feedPosts = action.payload?.data;
        } else {
          state.feedPosts = [...state.feedPosts, ...action.payload?.data || []];
        }

        state.postDataFetched = true;
      })
      .addCase(fetchMemberFeed.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

// Export reducer
export default profileSlice.reducer;
