import  NoAddressesIcon  from '@/assets/images/no-address.svg';
// src/store/crud.ts
import axiosInstance from '@/services/axiosClient';
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import Swal from 'sweetalert2';
import { setLocation } from './locationSlice';
import toast from 'react-hot-toast';
import { useTranslations } from 'next-intl';


interface AddItemProps {
    id: any;
}

interface CrudState {
    mainLoader: boolean;
    openModal: boolean;
    allAddressesItems:any;
    singleItem:any;
    startStep:number;
    itemId:AddItemProps | null;
}

const initialState: CrudState = {
    mainLoader: true,
    allAddressesItems:[],
    itemId:null,
    singleItem:{},
    openModal:false,
    startStep:0,

};


// Thunk for fetching items with pagination
export const getAllAddressesItems = createAsyncThunk(
    'address/getAllAddressesItems',
    async (_,{ rejectWithValue }) => {
        try {
            const { data } = await axiosInstance.get(`/locations`);
            return data?.data || [];
        } catch (error: any) {
            toast.error(error?.response?.data?.message);
            return rejectWithValue(error.message);
        }
    }
);

export const getAddressById = createAsyncThunk(
    'address/getAddressById',
    async ({data}:any,{ rejectWithValue }) => {
        try {
            // const { data } = await axiosInstance.get(`/locations/${id}`);
            return data;
        } catch (error: any) {
            toast.error(error?.response?.data?.message);
            return rejectWithValue(error.message);
        }
    }
);

// Thunk for adding an item
export const toggleItemToDefault = createAsyncThunk(
  'address/toggleItemToDefault',
  async ({ id }: any, { rejectWithValue, dispatch }) => {
    try {
      const { data } = await axiosInstance.patch(`locations/${id}/setDefault`, { is_default: 1 });

      if (data?.status === "success") {
        dispatch(setLocation({
          lat:data?.data?.lat,
          lng:data?.data?.lng,
          location_description:data?.data?.location,
          id:data?.data?.id
        }));
        return id 
        
      }

    } catch (error: any) {
        toast.error(error?.response?.data?.message);
      return rejectWithValue(error.message);
    }
  }
);

// Thunk for adding an item
export const deleteItemFromAddress = createAsyncThunk(
  'address/deleteItemFromAddress',
  async ({ id,t }: any, { rejectWithValue, dispatch }) => {
      // const t = useTranslations();
        try {
          const { data } = await axiosInstance.delete(`locations/${id}`);
          console.log("🚀 ~ data:", data)
          if (data?.status === "success") {
            dispatch(getAllAddressesItems());
             Swal.fire({
              title: t("Messages.deleteAddressSuccessfully"),
              icon: "success",
              showConfirmButton: false,
              timer: 1500,
            });
            return data?.data;
          }
        } catch (error: any) {
          Swal.fire({
            title: error?.response?.data?.message,
            icon: "error",
            showConfirmButton: false,
            timer: 1500,
          });
          return rejectWithValue(error.message);
        }
  }
);

export const addOrUpdateItemToAddresses = createAsyncThunk(
  "address/addOrUpdateItemToAddresses",
  async ({ id, values }: { id?: string; values: any; }, { rejectWithValue, dispatch }) => {
    try {
      const endpoint = id ? `locations/${id}` : `locations`;
      const method = id ? axiosInstance.put : axiosInstance.post;

      // Make API call based on condition
      const response = await method(endpoint, values);

      if (response?.data?.status === "success") {
        // Dispatch to refresh address list
        dispatch(getAllAddressesItems());
        if(values?.is_default){
          dispatch(setLocation({
            lat:values?.lat,
            lng:values?.lng,
            location_description:values?.location,
            id
          }));
        }
          dispatch(closeAddressModal())
      }
    } catch (error: any) {
        toast.error(error?.response?.data?.message);
      // Provide meaningful error message for better debugging
      const errorMessage = error.response?.data?.message || error.message || "حدث خطأ ما. حاول مجدداً.";
      return rejectWithValue(errorMessage);
    }
  }
);


// Slice
const addressSlice = createSlice({
    name: 'address',
    initialState,
    reducers: {
    openAddressModal : (state,action: PayloadAction<any>) =>{
        state.openModal = true;
        state.startStep = action?.payload?.step;
        state.singleItem = null;
    },
    closeAddressModal : (state) =>{
        state.openModal = false;
        state.startStep = 0;
        state.singleItem = null;
    },
    getSelectedItem : (state,action:PayloadAction<any>)=>{
      state.openModal = true;
      state.singleItem = action?.payload?.data;
      state.startStep = action?.payload?.step;
    }
    },
    extraReducers: (builder) => {
        builder
            .addCase(getAllAddressesItems.pending, (state) => {
                state.mainLoader = true;
            })
            .addCase(getAllAddressesItems.fulfilled,(state,action) => {
                state.mainLoader = false;
                state.allAddressesItems = action.payload
            })
            .addCase(getAllAddressesItems.rejected, (state) => {
                state.mainLoader = false;
            })
            .addCase(getAddressById.pending, (state) => {
                state.mainLoader = true;
            })
            .addCase(getAddressById.fulfilled,(state,action) => {
                state.mainLoader = false;
                state.singleItem = action.payload;
            })
            .addCase(getAddressById.rejected, (state) => {
                state.mainLoader = false;
            })
            .addCase(toggleItemToDefault.pending, (state) => {
                state.mainLoader = false;
            })
            .addCase(toggleItemToDefault.fulfilled, (state, action) => {
                state.mainLoader = false;
                state.allAddressesItems =  state.allAddressesItems.map((item:any) => item.id == action.payload ? { ...item, is_default: true } :  { ...item, is_default: false }); 
            })
            .addCase(toggleItemToDefault.rejected, (state) => {
                state.mainLoader = false;
            })
            .addCase(addOrUpdateItemToAddresses.pending, (state) => {
                state.mainLoader = true;
            })
            .addCase(addOrUpdateItemToAddresses.fulfilled, (state, action) => {
                state.mainLoader = false;
            })
            .addCase(addOrUpdateItemToAddresses.rejected, (state) => {
                state.mainLoader = false;
            })
            .addCase(deleteItemFromAddress.pending, (state) => {
                // state.mainLoader = true;
            })
            .addCase(deleteItemFromAddress.fulfilled, (state, action) => {
                // state.mainLoader = false;
                if(action.payload){
                  state.allAddressesItems = action.payload
                }
            })
            .addCase(deleteItemFromAddress.rejected, (state) => {
                // state.mainLoader = false;
            })
    },
});

export const { closeAddressModal,openAddressModal,getSelectedItem } = addressSlice.actions;
export default addressSlice.reducer;
