import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import axiosInstance from "../../utils/axiosConfig";
import { toast } from 'react-toastify';
import endpoints from "../../config/apiEndpoints";

interface RegistrationStep4State {
    userData: Record<string, string>;
    verifiedData: Record<string, boolean>;
    convenientTime: string | null;
    convenient_time_start: string | null;
    convenient_time_end: string | null;
    showVerifyModal: boolean;
    loading: boolean;
    error: string | null;
    dataFetched: boolean;
    otpSent: boolean;
    verifying: boolean;
  }

  const initialVerifiedData: Record<string, boolean> = {
    mobile: false,
    email: false,
    guardian: false,
  };

  const initialUserData: Record<string, string> = {
    mobile: '',
    email: '',
    whatsapp: '',
    guardian_phone: '',
  };

  const initialState: RegistrationStep4State = {
    userData: initialUserData,
    verifiedData: initialVerifiedData,
    convenientTime: 'any',
    convenient_time_start: '',
    convenient_time_end: '',
    showVerifyModal: false,
    loading: false,
    error: null,
    dataFetched: false,
    otpSent: false,
    verifying: false
  };
  const { registrationstep4Get: registrationstep4GetApi, registrationstep4Update: registrationstep4UpdateApi, sendOtp: sendOtpApi, completeRegistrationStep: completeRegistrationStepApi } = endpoints;

  export const fetchRegistrationStep4Data = createAsyncThunk(
    'registrationStep4/fetchData',
    async (_, { rejectWithValue }) => {
      try {
        const response = await axiosInstance.get(registrationstep4GetApi);
        console.log(response.data.data);
        return response.data.data;
      } catch (error) {
        console.error('Error fetching registration step 2 data:', error);
        return rejectWithValue((error as Error).message);
      }
    }
  );

  export const updateRegistrationStep4ToAPI = createAsyncThunk(
    'registrationStep4/updateFieldAndSave',
    async (payload: Record<string, string>, { rejectWithValue }) => {
      try {
        const response = await axiosInstance.post(
          registrationstep4UpdateApi,
          payload
        );
        console.log(response.data);
        return response.data;
      } catch (error) {
        console.error('Error updating field:', error);
        return rejectWithValue((error as Error).message);
      }
    }
  );

  export const sendOtp = createAsyncThunk(
    'registrationStep4/sendOtp',
    async (payload: Record<string, string>, { rejectWithValue }) => {
      try {
        const response = await axiosInstance.post(
          sendOtpApi,
          payload
        );
        toast.success(response.data?.message || 'OTP sent successfully');
        return response.data;
      } catch (error: unknown) {
        const err = error as { 
          response?: { 
            data?: { message?: string },
            status?: number 
          } 
        };
        const errorMessage = err.response?.data?.message || 'Failed to send OTP. Please try again later.';

        toast.error(`${errorMessage}`);
        return rejectWithValue((error as Error).message);
      }
    }
  );
  export const verifyOtp = createAsyncThunk(
    'registrationStep4/verifyOtp',
    async (payload: { type: string, otp: string }, { dispatch, rejectWithValue }) => {
      try {
        const response = await axiosInstance.post(
          '/member/verify-otp',
          payload
        );
        console.log(response.data);
        
        // Update verification status and close modal on success
        dispatch(setVerifiedData({ field: payload.type, value: true }));
        dispatch(setShowVerifyModal(false));
        
        // Show success message
        toast.success(response.data?.message || 'OTP verified successfully');
        return response.data;
      } catch (error: unknown) {
        // Improved error handling for Axios errors
        const err = error as { 
          message?: string,
          name?: string,
          code?: string,
          response?: { 
            data?: { 
              message?: string,
              errors?: Record<string, string[]>
            },
            status?: number 
          } 
        };
        console.log(error);
        
        // Get detailed error message
        let errorMessage = 'Failed to verify OTP. Please try again.';
        
        // Check for API error message
        if (err.response?.data?.message) {
          errorMessage = err.response.data.message;
        } 
        // Check for validation errors (common with 422 status)
        else if (err.response?.data?.errors) {
          const errors = err.response.data.errors;
          const firstError = Object.values(errors)[0];
          if (firstError && firstError.length > 0) {
            errorMessage = firstError[0];
          }
        }
        
        toast.error(errorMessage);
        return rejectWithValue(errorMessage);
      }
    }
  );

  export const completeRegistrationStep4 = createAsyncThunk(
    'registrationStep4/complete',
    async (_, { rejectWithValue }) => {
      try {
        const url = completeRegistrationStepApi.replace(':step', String(4));
        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 registrationStep4Slice = createSlice({
    name: 'registrationStep1',
    initialState,
    reducers: {
        setConvenientTime: (
            state,
            action: PayloadAction<string>
          ) => {
            state.convenientTime = action.payload;
          },
          setShowVerifyModal: (
            state,
            action: PayloadAction<boolean>
          ) => {
            state.showVerifyModal = action.payload;
          },
          setOtpSent: (
            state,
            action: PayloadAction<boolean>
          ) => {
            state.otpSent = action.payload;
          },
          setVerifiedData: (
            state,
            action: PayloadAction<{field: string, value: boolean}>
          ) => {
            const { field, value } = action.payload;
            if (field in state.verifiedData) {
              state.verifiedData[field] = value;
            }
          },
          setConvenientStartAndEnd: (
            state,
            action: PayloadAction<{field: string, value: string}>
          ) => {
            const { field, value } = action.payload;
            if (field === 'start') {
              state.convenient_time_start = value;
            } else if (field === 'end') {
              state.convenient_time_end = value;
            }
          },
        updateUserData: (
          state, action: PayloadAction<Record<string, string>>
        ) => {
          const updates = action.payload;
          Object.keys(updates).forEach(fieldName => {
            if (fieldName in state.userData) {
              state.userData[fieldName] = updates[fieldName];
            }
          });
        },
    },
    extraReducers: (builder) => {
        builder
        .addCase(fetchRegistrationStep4Data.pending, (state) => {
          state.loading = true;
          state.error = null;
        })
        .addCase(fetchRegistrationStep4Data.fulfilled, (state, action) => {
          state.loading = false;
          
          if (action.payload && action.payload.user_data) {
            const userData = action.payload.user_data;
            const verifiedData = action.payload?.verified_data;
            Object.keys(userData).forEach((key) => {
              if (key in state.userData) {
                state.userData[key] = userData[key];
              }
            });
            Object.keys(verifiedData).forEach((key) => {
              if (key in state.verifiedData) {
                state.verifiedData[key] = verifiedData[key];
              }
            });
          }

          if(action.payload?.convenient_time){
            state.convenientTime = action.payload?.convenient_time;
          }
          if(action.payload?.convenient_time_start){
            state.convenient_time_start = action.payload?.convenient_time_start; 
          }
          if(action.payload?.convenient_time_end){
            state.convenient_time_end = action.payload?.convenient_time_end; 
          }
          
          state.dataFetched = true;
        })
        .addCase(fetchRegistrationStep4Data.rejected, (state, action) => {
          state.loading = false;
          state.error = action.payload as string;
        })
        .addCase(verifyOtp.pending, (state) => {
          state.verifying = true;
          state.error = null;
        })
        .addCase(verifyOtp.fulfilled, (state) => {
          state.verifying = false;
          state.otpSent = false;
        })
        .addCase(verifyOtp.rejected, (state, action) => {
          state.verifying = false;
          state.error = action.payload as string;
        }); 
    }
  });

  export const {
    setConvenientTime,
    updateUserData,
    setShowVerifyModal,
    setVerifiedData,
    setOtpSent,
    setConvenientStartAndEnd
  } = registrationStep4Slice.actions;
  
  // Export reducer
  export default registrationStep4Slice.reducer;