import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import axiosInstance from "../../utils/axiosConfig";
import endpoints from "../../config/apiEndpoints";

interface FormField {
    label: string;
    value: string | number | { id: number, name: string };
    placeholder: string;
    required: boolean;
  }

interface CandidateInformationState {
    formFields: Record<string, FormField>;
    isCompleted: boolean;
    isModalOpen: boolean;
    loading: boolean;
    error: string | null;
    dataFetched: boolean;
  }

  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,
    },
    government_id: {
      label: 'Government ID',
      value: '',
      placeholder: 'Write candidate government ID number',
      required: true,
    }
  };

const initialState: CandidateInformationState = {
    formFields: initialFormFields,
    isCompleted: false,
    isModalOpen: false,
    loading: false,
    error: null,
    dataFetched: false,
  };

  const { registrationstep1Get: registrationstep1GetApi} = endpoints;

  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);
      }
    }
  );

  const candidateInformationSlice = createSlice({
    name: 'candidateinformation',
    initialState,
    reducers: {
        setIsModalOpen: (state, action: PayloadAction<boolean>) => {
            state.isModalOpen = action.payload;
          },
          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;
            }
          },
    },
    extraReducers: (builder) => {
      builder
        .addCase(fetchRegistrationStep1Data.pending, (state) => {
          state.loading = true;
          state.error = null;
        })
        .addCase(fetchRegistrationStep1Data.fulfilled, (state, action) => {
          state.loading = false;
          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];
              }
            });
          } 
          state.dataFetched = true;
        }) 
        .addCase(fetchRegistrationStep1Data.rejected, (state, action) => {
          state.loading = false;
          state.error = action.payload as string;
        });
    }
  });

  export const {setIsModalOpen , updateFormField} = candidateInformationSlice.actions;
  
  // Export reducer
  export default candidateInformationSlice.reducer;