import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axiosInstance from '../../utils/axiosConfig';
import endpoints from '../../config/apiEndpoints';

// Define the type for a single form field
interface FormField {
  label: string;
  value: string | number | { id: number, name: string };
  placeholder: string;
  required: boolean;
}
interface GuardianContact {
  label: string;
  value: string | number;
  placeholder: string;
}

// Define the state structure for registration step 2
interface RegistrationStep1State {
  lookingForMarriage: 'yes' | 'no';
  profileFor: 'myself' | 'others';
  guardian_type?: string | null;
  purpose?: string | null;
  guardian_picture?: string | null;
  guardian_verification_image?: string | null;
  guardian_contact?: Record<string, GuardianContact> | null;
  formFields: Record<string, FormField>;
  guardianFields: Record<string, FormField>;
  lookingForNoFields: Record<string, FormField>;
  isCompleted: boolean;
  isModalOpen: boolean;
  activeField: string;
  loading: boolean;
  error: string | null;
  dataFetched: boolean;
}

// Initial form fields
const initialFormFields: Record<string, FormField> = {
  nickname: {
    label: 'Nickname',
    value: '',
    placeholder: 'Enter your nickname',
    required: true,
  },
  fullName: {
    label: 'Full name',
    value: '',
    placeholder: 'Write your full name',
    required: true,
  },
  gender: {
    label: 'Gender',
    value: '',
    placeholder: 'Select your gender',
    required: true,
  },
  dateOfBirth: {
    label: 'Date of Birth',
    value: '',
    placeholder: 'Select your birthday',
    required: true,
  },
  height: {
    label: 'Height',
    value: '',
    placeholder: 'Select your height',
    required: true,
  },
  bloodGroup: {
    label: 'Blood Group',
    value: '',
    placeholder: 'Select your blood group',
    required: true,
  },
  maritalStatus: {
    label: 'Marital Status',
    value: { id: 0, name: '' },
    placeholder: 'Select your marital status',
    required: true,
  },
  motherTongue: {
    label: 'Mother Tongue',
    value: '',
    placeholder: 'Select your mother tongue',
    required: true,
  },
  religion: {
    label: 'Religion',
    value: '',
    placeholder: 'Select your religion',
    required: true,
  },
  profession: {
    label: 'Profession',
    value: { id: 0, name: '' },
    placeholder: 'Describe your professional experience and skills',
    required: true,
  },
  income: {
    label: 'Income',
    value: '',
    placeholder: 'Add your monthly income',
    required: true,
  },
  education: {
    label: 'Education',
    value: '',
    placeholder: 'Describe your highest education',
    required: true,
  },
  smoking: {
    label: 'Smoking',
    value: '',
    placeholder: 'Do you smoke?',
    required: true,
  },
  drink: {
    label: 'Drink',
    value: '',
    placeholder: 'Do you drink?',
    required: true,
  },
  currentLocation: {
    label: 'Current Location',
    value: '',
    placeholder: 'Where are you now?',
    required: true,
  },
  citizenshipCountry: {
    label: 'Citizenship Country',
    value: '',
    placeholder: 'What\'s your nationality?',
    required: true,
  },
  hometown: {
    label: 'Hometown',
    value: '',
    placeholder: 'Where is your hometown?',
    required: true,
  },
};
const initialGuardianFields: Record<string, FormField> = {
  guardian_full_name: {
    label: 'Guardian Full Name',
    value: '',
    placeholder: 'Enter guardian\'s full name',
    required: true,
  },
  guardian_gender: {
    label: 'Guardian Gender',
    value: '',
    placeholder: 'Select guardian\'s gender',
    required: true,
  },
  guardian_date_of_birth: {
    label: 'Guardian Date of Birth',
    value: '',
    placeholder: 'Select guardian\'s birthday',
    required: true,
  },
  guardian_current_location: {
    label: 'Guardian Current Location',
    value: '',
    placeholder: 'Update Current Location',
    required: true,
  },
  guardian_govt_id: {
    label: 'Guardian Government ID',
    value: '',
    placeholder: 'Enter guardian\'s government ID',
    required: true,
  }
}
const lookingForNoFields: Record<string, FormField> = {
  fullName: {
    label: 'Full name',
    value: '',
    placeholder: 'Write your full name',
    required: true,
  },
  gender: {
    label: 'Gender',
    value: '',
    placeholder: 'Select your gender',
    required: true,
  },
  dateOfBirth: {
    label: 'Date of Birth',
    value: '',
    placeholder: 'Select your birthday',
    required: true,
  },
  currentLocation: {
    label: 'Current Location',
    value: '',
    placeholder: 'Where are you now?',
    required: true,
  },
  govt_id: {
    label: 'Government ID',
    value: '',
    placeholder: 'Enter government ID',
    required: true,
  }
}

// Initial state
const initialState: RegistrationStep1State = {
  lookingForMarriage: 'yes',
  profileFor: 'myself',
  guardian_type: '',
  purpose: '',
  guardian_picture: null,
  guardian_verification_image: null,
  guardian_contact: null,
  formFields: initialFormFields,
  guardianFields: initialGuardianFields,
  lookingForNoFields: lookingForNoFields,
  isCompleted: false,
  activeField: '',
  isModalOpen: false,
  loading: false,
  error: null,
  dataFetched: false,
};

const { registrationstep1Get: registrationstep1GetApi, registrationstep1Update: registrationstep1UpdateApi, completeRegistrationStep: completeRegistrationStepApi } = endpoints;

// Async thunk to fetch registration step 2 data
export const fetchRegistrationStep1Data = createAsyncThunk(
  'registrationStep1/fetchData',
  async (_, { rejectWithValue }) => {
    try {
      const response = await axiosInstance.get(registrationstep1GetApi);
      return response.data.data;
    } catch (error) {
      console.error('Error fetching registration step 2 data:', error);
      return rejectWithValue((error as Error).message);
    }
  }
);

export const updateFieldAndSaveToAPI = createAsyncThunk(
  'registrationStep1/updateFieldAndSave',
  async (payload: { fieldName: string; value:{ id?: number, name?: string, permanent_country?: number, permanent_state?: number, permanent_city?: number, nickname?: string, fullName?: string, gender?: number, dateOfBirth?: string, height?: string, bloodGroup?: string, maritalStatus?: number, motherTongue?: number, religion?: number, profession?: string, income?: string, education?: number, smoking?: string, drink?: string, current_latitude?: number, current_longitude?: number, current_sublocality?: string , citizenshipCountry?: number, guardian_type?: number, guardian_gender?: number, guardian_date_of_birth?: string , guardian_current_latitude?: number, guardian_current_longitude?: number, guardian_current_sublocality?: string, purpose?: string, guardian_full_name?: string, guardian_govt_id_type?: string, guardian_govt_id_number?: string, guardian_govt_id_front?: File, guardian_govt_id_back?: File, govt_id_type?: string, govt_id_number?: string, govt_id_front?: File, govt_id_back?: File } }, { rejectWithValue }) => {
    try {
      // Check if we're handling file uploads for govt ID
      if (payload.value.guardian_govt_id_front || payload.value.guardian_govt_id_back || payload.value.govt_id_front || payload.value.govt_id_back) {
        const formData = new FormData();
        
        // Add govt_id_front file if it exists
        if (payload.value.guardian_govt_id_front) {
          formData.append('guardian_govt_id_front', payload.value.guardian_govt_id_front);
        }
        
        // Add govt_id_back file if it exists
        if (payload.value.guardian_govt_id_back) {
          formData.append('guardian_govt_id_back', payload.value.guardian_govt_id_back);
        }
        if (payload.value.govt_id_front) {
          formData.append('guardian_govt_id_front', payload.value.govt_id_front);
        }
        
        // Add govt_id_back file if it exists
        if (payload.value.govt_id_back) {
          formData.append('govt_id_back', payload.value.govt_id_back);
        }
        
        const response = await axiosInstance.post(
          registrationstep1UpdateApi,
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data',
            },
          }
        );
        
        console.log(response.data);
        return response.data;
      } else {
        // Handle regular non-file data
        const response = await axiosInstance.post(
          registrationstep1UpdateApi,
          payload.value
        );
        console.log(response.data);
        return response.data;
      }
    } catch (error) {
      console.error('Error updating field:', error);
      return rejectWithValue((error as Error).message);
    }
  }
);

export const completeRegistrationStep1 = createAsyncThunk(
  'registrationStep1/complete',
  async (_, { rejectWithValue }) => {
    try {
      const url = completeRegistrationStepApi.replace(':step', String(1));
      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 registrationStep1Slice = createSlice({
  name: 'registrationStep1',
  initialState,
  reducers: {
    // Update a single form field
    updateFormField: (
      state,
      action: PayloadAction<{ fieldName: string; value: string | number | { id: number, name: string } }>
    ) => {
      const { fieldName, value } = action.payload;
      if (state.formFields[fieldName]) {
        state.formFields[fieldName].value = value;
      }

      if (state.guardianFields[fieldName]) {
        state.guardianFields[fieldName].value = value;
      }

      if (state.lookingForNoFields[fieldName]) {
        state.lookingForNoFields[fieldName].value = value;
      }

    },
    
    updateFormFields: (
      state,
      action: PayloadAction<Record<string, string>>
    ) => {
      const updates = action.payload;
      Object.keys(updates).forEach(fieldName => {
        if (state.formFields[fieldName]) {
          state.formFields[fieldName].value = updates[fieldName];
        }

        if (state.guardianFields[fieldName]) {
          state.guardianFields[fieldName].value = updates[fieldName];
        }

        if (state.lookingForNoFields[fieldName]) {
          state.lookingForNoFields[fieldName].value = updates[fieldName];
        }
      });
    },
    
    // Set looking for marriage status
    setLookingForMarriage: (
      state,
      action: PayloadAction<'yes' | 'no'>
    ) => {
      state.lookingForMarriage = action.payload;
    },
    
    // Set profile for
    setProfileFor: (
      state,
      action: PayloadAction<'myself' | 'others'>
    ) => {
      state.profileFor = action.payload;
    },

    setPurpose: (state, action: PayloadAction<string>) => {
      state.purpose = action.payload;
    },
    setGuardianType: (state, action: PayloadAction<string>) => {
      state.guardian_type = action.payload;
    },
    // Mark step as completed
    setStepCompleted: (state, action: PayloadAction<boolean>) => {
      state.isCompleted = action.payload;
    },

    setIsModalOpen: (state, action: PayloadAction<boolean>) => {
      state.isModalOpen = action.payload;
    },

    setActiveField: (state, action: PayloadAction<string>) => {
      state.activeField = action.payload;
    },
    
    // Reset the entire form
    resetForm: () => {
      return initialState;
    },
    
    // Check if all required fields are filled
    checkCompletion: (state) => {
      const requiredFields = Object.values(state.formFields).filter(
        field => field.required
      );
      
      const allRequiredFieldsFilled = requiredFields.every(
        field => typeof field.value === 'string' ? field.value.trim() !== '' : field.value !== 0
      );
      
      state.isCompleted = allRequiredFieldsFilled;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchRegistrationStep1Data.pending, (state) => {
        state.loading = true;
        state.error = null;
        // state.dataFetched = false;
      })
      .addCase(fetchRegistrationStep1Data.fulfilled, (state, action) => {
        state.loading = false;
        
        // Set state properties from payload
        if(action.payload?.guardian_type){
          state.guardian_type = action.payload.guardian_type;
        }

        if(action.payload?.purpose){
          state.purpose = action.payload.purpose;
          if(action.payload.purpose != 'member'){
            state.lookingForMarriage = 'no';
          }
        }
        
        if (action.payload && action.payload.user_data) {
          const userData = action.payload.user_data;
          Object.keys(userData).forEach(key => {
            if (state.formFields[key]) {
              state.formFields[key].value = userData[key];
            }
          });
          Object.keys(userData).forEach(key => {
            if (state.lookingForNoFields[key]) {
              state.lookingForNoFields[key].value = userData[key];
            }
          });
        }

        if(action.payload && action.payload.guardian_data){
          const guardianData = action.payload.guardian_data;
          Object.keys(guardianData).forEach(key => {
            if (state.guardianFields[key]) {
              state.guardianFields[key].value = guardianData[key];
            } 
          })
        }
        
        if(action.payload?.profile_for){
          state.profileFor = action.payload.profile_for;
        }

        state.dataFetched = true;
      })
      .addCase(fetchRegistrationStep1Data.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      // Add these cases for the updateFieldAndSaveToAPI thunk
      .addCase(updateFieldAndSaveToAPI.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(updateFieldAndSaveToAPI.fulfilled, (state) => {
        state.loading = false;
      })
      .addCase(updateFieldAndSaveToAPI.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  }
});

// Export actions
export const {
  updateFormField,
  updateFormFields,
  setLookingForMarriage,
  setProfileFor,
  setStepCompleted,
  resetForm,
  checkCompletion,
  setIsModalOpen,
  setActiveField,
  setGuardianType,
  setPurpose
} = registrationStep1Slice.actions;

// Export reducer
export default registrationStep1Slice.reducer;