import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axiosInstance from '../../utils/axiosConfig';
import endpoints from '../../config/apiEndpoints';

export interface PhotosState {
  coverPhoto?: string | ArrayBuffer | null;
  profilePicture?: string | ArrayBuffer | null;
  gallery_image_1?: string | ArrayBuffer | null;
  gallery_image_2?: string | ArrayBuffer | null;
  blur_photos?: string | number;
}

interface FormField {
  label: string;
  value: string | number | { id: number, name: string } | null;
  placeholder: string;
  required: boolean;
}

// Define the state structure for registration step 3
interface RegistrationStep2State {
  photos: PhotosState;
  formFields: Record<string, FormField>;
  isCompleted: boolean;
  isModalOpen: boolean;
  loading: boolean;
  error: string | null;
  dataFetched: boolean;
  blurPhotos: string;
  isBlurModalOpen: boolean;
}

// Initial state
const initialState: RegistrationStep2State = {
  photos: {
    coverPhoto: null,
    profilePicture: null,
    gallery_image_1: null,
    gallery_image_2: null
  },
  formFields: {},
  isCompleted: false,
  isModalOpen: false,
  loading: false,
  error: null,
  dataFetched: false,
  blurPhotos: 'public',
  isBlurModalOpen: false
};
const { registrationstep2Get: registrationstep2GetApi, registrationstep2Update: registrationstep2UpdateApi, completeRegistrationStep: completeRegistrationStepApi } = endpoints;

export const fetchRegistrationStep2Data = createAsyncThunk(
  'registrationStep2/fetchData',
  async (_, { rejectWithValue }) => {
    try {
      const response = await axiosInstance.get(registrationstep2GetApi);
      return response.data.data;
    } catch (error) {
      console.error('Error fetching registration step 2 data:', error);
      return rejectWithValue((error as Error).message);
    }
  }
);
// Async thunk for uploading photos
export const uploadPhotos = createAsyncThunk(
  'registrationStep2/uploadPhotos',
  async (photos: PhotosState, { rejectWithValue }) => {
    try {
      const formData = new FormData();
      if (photos.coverPhoto && photos.coverPhoto.toString().startsWith('data:image')) {
        const coverPhotoBlob = await fetch(photos.coverPhoto.toString()).then(r => r.blob());
        formData.append('cover_photo', coverPhotoBlob, 'cover_photo.jpg');
      }
    
      if (photos.profilePicture && photos.profilePicture.toString().startsWith('data:image')) {
        const profilePictureBlob = await fetch(photos.profilePicture.toString()).then(r => r.blob());
        formData.append('profile_picture', profilePictureBlob, 'profile_picture.jpg');
      }

      if (photos.gallery_image_1 && photos.gallery_image_1.toString().startsWith('data:image')) {
        const galleryImage1Blob = await fetch(photos.gallery_image_1.toString()).then(r => r.blob());
        formData.append('gallery_image_1', galleryImage1Blob, 'gallery_image_1.jpg');
      }
      
      if (photos.gallery_image_2 && photos.gallery_image_2.toString().startsWith('data:image')) {
        const galleryImage2Blob = await fetch(photos.gallery_image_2.toString()).then(r => r.blob());
        formData.append('gallery_image_2', galleryImage2Blob, 'gallery_image_2.jpg');
      }
      
      if(photos.blur_photos != null){
        formData.append('blur_photos', photos.blur_photos.toString());
      }
      const response = await axiosInstance.post(
        registrationstep2UpdateApi,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        }
      );
      return response.data;
    } catch (error) {
      console.error('Error uploading photos:', error);
      return rejectWithValue((error as Error).message);
    }
  }
);

export const completeRegistrationStep2 = createAsyncThunk(
  'registrationStep2/complete',
  async (_, { rejectWithValue }) => {
    try {
      const url = completeRegistrationStepApi.replace(':step', String(2));
      const response = await axiosInstance.get(url);
      console.log(response.data);
      if(response.data?.user){
        localStorage.setItem('user', JSON.stringify(response.data?.user));
      } 
      return response.data.data;
    } catch (error) {
      console.error('Error fetching registration step 2 data:', error);
      return rejectWithValue((error as Error).message);
    }
  }
);

// Create the slice
const registrationStep2Slice = createSlice({
  name: 'registrationStep2',
  initialState,
  reducers: {
    updatePhotos: (state, action: PayloadAction<Partial<PhotosState>>) => {
      state.photos = { ...state.photos, ...action.payload };
    },
    updatePhoto: (state, action: PayloadAction<{ type: string; index?: number; value: string | ArrayBuffer | null }>) => {
      const { type, value } = action.payload;
      
      if (type === 'coverPhoto') {
        state.photos.coverPhoto = value;
      } else if (type === 'profilePicture') {
        state.photos.profilePicture = value;
      } else if (type === 'gallery_image_1') {
        state.photos.gallery_image_1 = value;
      } else if (type === 'gallery_image_2') {
        state.photos.gallery_image_2 = value;
      }
    },
    toggleBlurPhotos: (state, action: PayloadAction<string>) => {
      state.blurPhotos = action.payload;
      if (action.payload === 'public') {
        state.isBlurModalOpen = false;
      }
    },
    toggleBlurModal: (state, action: PayloadAction<boolean>) => {
      state.isBlurModalOpen = action.payload;
    },
    setStepCompleted: (state, action: PayloadAction<boolean>) => {
      state.isCompleted = action.payload;
    },
    toggleModal: (state) => {
      state.isModalOpen = !state.isModalOpen;
    },
    resetStep3: () => initialState
  },
  extraReducers: (builder) => {
    builder
      .addCase(uploadPhotos.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(uploadPhotos.fulfilled, (state, action) => {
        console.log(action.payload)
        state.loading = false;
        state.isCompleted = true;
        state.dataFetched = true;
      })
      .addCase(uploadPhotos.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      .addCase(fetchRegistrationStep2Data.pending, (state) => {
        state.error = null;
      })
      .addCase(fetchRegistrationStep2Data.fulfilled, (state, action) => {
        state.loading = false;
        if(action.payload?.photos?.profile_picture){
          state.photos.profilePicture = action.payload?.photos?.profile_picture;
        }
        if(action.payload?.photos?.cover_photo){
          state.photos.coverPhoto = action.payload?.photos?.cover_photo;
        }
        if(action.payload?.photos?.gallery_image_1){
          state.photos.gallery_image_1 = action.payload?.photos?.gallery_image_1;
        }

        if(action.payload?.photos?.gallery_image_2){
          state.photos.gallery_image_2 = action.payload?.photos?.gallery_image_2;
        }

        if(action.payload?.photos?.blur_photos){
          state.blurPhotos = action.payload?.photos?.blur_photos;
        }
        state.dataFetched = true;
      })
      .addCase(fetchRegistrationStep2Data.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  }
});

export const { 
  updatePhotos, 
  updatePhoto, 
  toggleBlurPhotos, 
  setStepCompleted, 
  toggleModal,
  resetStep3,
  toggleBlurModal
} = registrationStep2Slice.actions;

export default registrationStep2Slice.reducer;