import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { isAxiosError } from "axios";
import { axiosBuzz, axiosBuzzOne } from "../utils/axios";

export const getAkademyPlans = createAsyncThunk(
  `COMMON/akademy/plans`,
  async (payload) => {
    try {
      const response = await axiosBuzzOne({
        method: "GET",
        url: "/akademy/subscriptions/plans",
      });
      return response.data;
    } catch (err) {
      console.log(err);
      if (isAxiosError(err))
        throw new Error(err.response.data.message || "Something went wrong");
      throw err;
    }
  }
);

export const getAkademyClasses = createAsyncThunk(
  `COMMON/akademy/classes`,
  async (payload) => {
    try {
      const response = await axiosBuzzOne({
        method: "GET",
        url: "/akademy/bcc/school/classes",
      });
      return response.data;
    } catch (err) {
      console.log(err);
      if (isAxiosError(err))
        throw new Error(err.response.data.message || "Something went wrong");
      throw err;
    }
  }
);

export const createPurchase = createAsyncThunk(
  `PURCHASE:POST/akademy/purchase`,
  async (payload) => {
    try {
      const response = await axiosBuzzOne({
        method: "POST",
        url: "/akademy/subscriptions/purchase",
      });
      return response.data;
    } catch (err) {
      console.log(err);
      if (isAxiosError(err))
        throw new Error(err.response.data.message || "Something went wrong");
      throw err;
    }
  }
);

export const updatePurchase = createAsyncThunk(
  `PURCHASE:PUT/akademy/purchase`,
  async (payload, { getState, dispatch }) => {
    const { purchase } = getState();

    try {
      const response = await axiosBuzzOne({
        method: "PUT",
        url: `/akademy/subscriptions/purchase/${purchase.purchaseId}/cart`,
        data: payload,
      });
      dispatch(getPurchaseDetails());
      return response.data;
    } catch (err) {
      console.log(err);
      if (isAxiosError(err))
        throw new Error(err.response.data.message || "Something went wrong");
      throw err;
    }
  }
);

export const removeItemFromCart = createAsyncThunk(
  `PURCHASE:DELETE/akademy/purchase`,
  async (payload, { getState, dispatch }) => {
    const { cartItemId } = payload;
    const { purchase } = getState();

    try {
      const response = await axiosBuzzOne({
        method: "DELETE",
        url: `/akademy/subscriptions/purchase/${purchase.purchaseId}/cart/${cartItemId}`,
        data: payload,
      });
      dispatch(getPurchaseDetails());
      return response.data;
    } catch (err) {
      console.log(err);
      if (isAxiosError(err))
        throw new Error(err.response.data.message || "Something went wrong");
      throw err;
    }
  }
);

export const getPurchaseDetails = createAsyncThunk(
  `PURCHASE:GET/akademy/purchase`,
  async (payload, { getState }) => {
    const { purchase } = getState();
    try {
      const response = await axiosBuzzOne({
        method: "GET",
        url: `/akademy/subscriptions/purchase/${purchase.purchaseId}/cart`,
      });
      return response.data;
    } catch (err) {
      console.log(err);
      if (isAxiosError(err))
        throw new Error(err.response.data.message || "Something went wrong");
      throw err;
    }
  }
);

export const initiatePayment = createAsyncThunk(
  `PURCHASE:POST/akademy/purchase/initiatePayment`,
  async (payload, { getState }) => {
    const { purchase } = getState();
    try {
      const response = await axiosBuzzOne({
        method: "POST",
        url: `/akademy/subscriptions/purchase/${purchase.purchaseId}/cart/checkout`,
      });
      return response.data;
    } catch (err) {
      console.log(err);
      if (isAxiosError(err))
        throw new Error(err.response.data.message || "Something went wrong");
      throw err;
    }
  }
);

export const verifyPayment = createAsyncThunk(
  `PURCHASE:POST/akademy/purchase/verifyPayment`,
  async (payload) => {
    try {
      const response = await axiosBuzz({
        method: "POST",
        url: "/payments/verify",
        data: {
          txnId: payload.txnId,
          provider: "airpay",
        },
      });
      return response.data;
    } catch (err) {
      console.log(err);
      if (isAxiosError(err))
        throw new Error(err.response.data.message || "Something went wrong");
      throw err;
    }
  }
);

export const validateCoupon = createAsyncThunk(
  `COUPON:POST/validate`,
  async (payload) => {
    try {
      const response = await axiosBuzzOne({
        method: "POST",
        url: "/offer/validate-coupon",
        data: {
          code: payload.couponCode,
        },
      });
      return response.data;
    } catch (err) {
      console.log(err);
      if (isAxiosError(err))
        throw new Error(err.response.data.message || "Something went wrong");
      throw err;
    }
  }
);

export const getAllTeenybeansLanguages = createAsyncThunk(
  `PURCHASE:getAllTeenybeansLanguages`,
  async (paylaod, { rejectWithValue }) => {
    try {
      const response = await axiosBuzzOne({
        method: "GET",
        url: "/akademy/bcc/user/languages",
      });
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

export const purchaseSlice = createSlice({
  name: "purchase",
  initialState: {
    currency: localStorage.getItem("currency") || "INR",
    planDetails: {},
    planPriceDetails: {
      RETAIL_PARENT: {},
      TUTION_EDUCATOR: {},
      ENTERPRISE_SCHOOL: {},
    },
    classes: [],
    purchaseId: localStorage.getItem("PURCHASE_ID"),
    purchaseDetails: {},
    userDetails:
      (localStorage.getItem("USER_DETAILS") &&
        JSON.parse(localStorage.getItem("USER_DETAILS"))) ||
      {},
    statusByName: {},
    teenybeansLanguages: [],
  },
  reducers: {
    clearPurchaseCart: (state, action) => {
      state.purchaseId = undefined;
      localStorage.removeItem("PURCHASE_ID");
      state.purchaseDetails = {};
      state.userDetails = {};
      localStorage.removeItem("USER_DETAILS");
      /////////////////////////////////////////////
      localStorage.removeItem("IS_USER_VERIFIED");
      localStorage.removeItem("IS_EMAIL_OTP_SENT");
    },

    saveUserDetails: (state, action) => {
      state.userDetails = action.payload;
      localStorage.setItem("USER_DETAILS", JSON.stringify(action.payload));
    },
  },

  extraReducers: (builder) => {
    builder.addCase(getAkademyPlans.pending, (state, action) => {
      state.statusByName["plans"] = "pending";
    });
    builder.addCase(getAkademyPlans.fulfilled, (state, action) => {
      state.statusByName["plans"] = "fulfilled";

      action.payload.data.map((plan) => {
        const { _id, products, productCategory } = plan;
        state.planDetails[_id] = plan;
        if (products && Array.isArray(products) && products.length == 1) {
          state.planPriceDetails[productCategory][products[0]] = plan;
        }
      });
    });
    builder.addCase(getAkademyPlans.rejected, (state, action) => {
      state.statusByName["plans"] = "rejected";
    });

    builder.addCase(getAkademyClasses.pending, (state, action) => {
      state.statusByName["classes"] = "pending";
    });
    builder.addCase(getAkademyClasses.fulfilled, (state, action) => {
      state.statusByName["classes"] = "fulfilled";
      state.classes = ["IK3", "IK2", "IK1", "PG"]?.map((item) =>
        action.payload.data?.find((el) => el.name === item)
      );
    });
    builder.addCase(getAkademyClasses.rejected, (state, action) => {
      state.statusByName["classes"] = "rejected";
    });

    builder.addCase(createPurchase.fulfilled, (state, action) => {
      const purchaseId = action.payload.data._id;
      state.purchaseId = purchaseId;
      localStorage.setItem("PURCHASE_ID", purchaseId);
    });

    builder.addCase(getPurchaseDetails.fulfilled, (state, action) => {
      state.purchaseDetails = action.payload.data.data[0];
      console.log("lookData", action.payload);
    });
    builder.addCase(getAllTeenybeansLanguages.fulfilled, (state, action) => {
      state.teenybeansLanguages = action.payload.data;
    });
  },
});

// Action creators are generated for each case reducer function
export const { saveUserDetails, clearPurchaseCart } = purchaseSlice.actions;

export default purchaseSlice.reducer;
