import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import axiosInstance from "../../utils/axiosConfig";
import endpoints from "../../config/apiEndpoints";

interface FormField {
    label: string;
    value: string;
    placeholder: string;
    required: boolean;
  }

interface RegistrationStep3State {
  formFields: Record<string, FormField>;
  isCompleted: boolean;
  isModalOpen: boolean;
  loading: boolean;
  error: string | null;
  dataFetched: boolean;
}

const initialFormFields: Record<string, FormField> = {
    age: {
      label: 'Age',
      value: '',
      placeholder: 'Select your partner age range',
      required: true,
    },
    height: {
      label: 'Height',
      value: '',
      placeholder: 'Select your partner height range',
      required: true,
    },
    maritalstatus: {
      label: 'Marital Status',
      value: '',
      placeholder: 'Select your partner marital status',
      required: true,
    },
    mothertongue: {
      label: 'Mother Tongue',
      value: '',
      placeholder: 'Select your partner mother tongue',
      required: true,
    },
    religion: {
      label: 'Religion',
      value: '',
      placeholder: 'Select your partner religion',
      required: true,
    },
    profession: {
      label: 'Profession',
      value: '',
      placeholder: 'Select your Partner profession',
      required: true,
    },
    income: {
      label: 'Income',
      value: '',
      placeholder: 'Select your partner income range',
      required: true,
    },
    education: {
      label: 'Education',
      value: '',
      placeholder: 'Select your partner minimum education',
      required: true,
    },
    smoking: {
      label: 'Smoking',
      value: '',
      placeholder: 'Select that smoking acceptable or not',
      required: true,
    },
    drink: {
      label: 'Drink',
      value: '',
      placeholder: 'Select that drinking acceptable or not',
      required: true,
    },
    country: {
      label: 'Country',
      value: '',
      placeholder: 'What is your preferred country for a partner?',
      required: true,
    }
  };

  const initialState: RegistrationStep3State = {
    formFields: initialFormFields,
    isCompleted: false,
    isModalOpen: false,
    loading: false,
    error: null,
    dataFetched: false,
  };
  const { registrationstep3Get: registrationstep3GetApi, registrationstep3Update: registrationstep3UpdateApi, completeRegistrationStep: completeRegistrationStepApi } = endpoints;

  export const fetchRegistrationStep3Data = createAsyncThunk(
    'registrationStep3/fetchData',
    async (_, { rejectWithValue }) => {
      try {
        const response = await axiosInstance.get(registrationstep3GetApi);
        return response.data.data;
      } catch (error) {
        console.error('Error fetching registration step 2 data:', error);
        return rejectWithValue((error as Error).message);
      }
    }
  );

  export const updateStep3DataToAPI = createAsyncThunk(
    'registrationStep3/updateStep3DataToAPI',
    async (payload: { 
      fieldName: string; 
      value: string | number  | { id?: number, name?: string , religion?: number , age_from?: number, age_to?: number, height_from?: string , height_to?: string, income?: string , marital_statuses?: Array<number>, professions?: Array<string>, education?: number, smoking?: string, drinking?: string, preferred_countries?: Array<number>, partner_mother_tongue?: Array<number>}
    }, { rejectWithValue }) => {
      try {
        const response = await axiosInstance.post(
          registrationstep3UpdateApi,
          payload.value
        );
        return response.data;
      } catch (error) {
        console.error('Error updating field:', error);
        return rejectWithValue((error as Error).message);
      }
    }
  );

  export const completeRegistrationStep3 = createAsyncThunk(
    'registrationStep2/complete',
    async (_, { rejectWithValue }) => {
      try {
        const url = completeRegistrationStepApi.replace(':step', String(3));
        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);
      }
    }
  );

  const registrationStep3Slice = createSlice({
    name: 'registrationStep3',
    initialState,
    reducers: {
      // Update a single form field
      updateFormField: (
        state,
        action: PayloadAction<{ fieldName: string; value: string }>
      ) => {
        const { fieldName, value } = action.payload;
        if (state.formFields[fieldName]) {
          state.formFields[fieldName].value = value;
        }
      },
      
      // Update multiple form fields at once
      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];
          }
        });
      },
      // Mark step as completed
      setStepCompleted: (state, action: PayloadAction<boolean>) => {
        state.isCompleted = action.payload;
      },
  
      setIsModalOpen: (state, action: PayloadAction<boolean>) => {
        state.isModalOpen = 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 => field.value.trim() !== ''
        );
        
        state.isCompleted = allRequiredFieldsFilled;
      },
    },
    extraReducers: (builder) => {
      builder
        .addCase(fetchRegistrationStep3Data.pending, (state) => {
          state.loading = true;
          state.error = null;
        })
        .addCase(fetchRegistrationStep3Data.fulfilled, (state, action) => {
          state.loading = false;
          if (action.payload && action.payload.partner_preference) {
            const partner_preference = action.payload.partner_preference;
            
            Object.keys(partner_preference).forEach(key => {
              if (state.formFields[key]) {
                state.formFields[key].value = partner_preference[key];
              }
            });
          }
          state.dataFetched = true;
        })
        .addCase(fetchRegistrationStep3Data.rejected, (state, action) => {
          state.loading = false;
          state.error = action.payload as string;
        })
        .addCase(updateStep3DataToAPI.pending, (state) => {
          state.loading = true;
          state.error = null;
        })
        .addCase(updateStep3DataToAPI.fulfilled, (state, action) => {
          state.loading = false;
          console.log(action.payload)
        })
        .addCase(updateStep3DataToAPI.rejected, (state, action) => {
          state.loading = false;
          state.error = action.payload as string;
        });
    }
  });

  // Export actions
export const {
    updateFormField,
    updateFormFields,
    setStepCompleted,
    resetForm,
    checkCompletion,
    setIsModalOpen
  } = registrationStep3Slice.actions;
  
  // Export reducer
  export default registrationStep3Slice.reducer;