import Axios from "axios";
import useAxios from "axios-hooks";
import { useCallback, useState } from "react";
import { getCookie } from "./getCookies";

const getApiBaseUrl = () =>
  window.location.hostname.includes("staging") ||
  window.location.hostname.includes("localhost")
    ? "https://dev-117782726-api.learngual.com"
    : "https://api.learngual.com";

const postDefaultAccountRequest = async (accountID) =>
  Axios({
    method: "POST",
    baseURL: getApiBaseUrl(),
    url: "/iam/v1/users/default_account/",
    params: {
      _account: accountID,
    },
    headers: {
      Authorization: `Bearer ${getCookie("access") ?? ""}`,
    },
  });

const useHeader = (props = { default: false }) => {
  // get user details
  const [userDetails, getUserDetails] = useAxios(
    {
      method: "get",
      url: "/iam/v1/users/me/",
    },
    {
      manual: !props.default,
    },
  );

  const handleGetUserDetails = useCallback(async () => {
    await getUserDetails({
      method: "get",
      url: "/iam/v1/users/me/",
    });
  }, [getUserDetails]);

  //get default affiliate account
  const [{ ...getDefaultAffiliateData }, getDefaultAffiliate] = useAxios(
    {
      method: "GET",
    },
    { manual: true },
  );
  const handleGetDefaultAffiliate = useCallback(async () => {
    try {
      return await getDefaultAffiliate({
        url: "/iam/v1/users/get_default_affiliate/",
      });
    } catch (error) {
      console.log(error);
    }
  }, [getDefaultAffiliate]);

  //set default affiliate account
  const [{ ...setDefaultAffiliateData }, setDefaultAffiliate] = useAxios(
    {
      method: "POST",
    },
    { manual: true },
  );
  const handleSetDefaultAffiliate = useCallback(async (data) => {
    return await setDefaultAffiliate({
      url: "/iam/v1/users/default_affiliate/",
      data,
    });
  }, [setDefaultAffiliate]);

  //get all affiliate account
  const [{ ...getAllAffiliateData }, getAllAffiliate] = useAxios(
    {
      method: "GET",
    },
    { manual: true },
  );
  const handleGetAllAffiliate = useCallback(async (params) => {
    return await getAllAffiliate({
      url: "/learn/v1/instructor/account/affiliate_enterprise_accounts/",
      params,
    });
  }, [getAllAffiliate]);

  const [{ ...retrieveUserDetailsData }, retrieveUserDetails] = useAxios();

  const handleRetrieveUserDetails = useCallback(async (data) => {
    await retrieveUserDetails({
      method: "patch",
      url: "/iam/v1/users/me/",
      data: {
        ...data,
      },
    });
  }, [retrieveUserDetails]);

  const [{ ...updateUserAccountData }, updateUserAccount] = useAxios();

  const handleUpdateUserAccount = useCallback(async (id, data) => {
    await updateUserAccount({
      method: "patch",
      url: `/iam/v1/accounts/${id}/`,
      data: {
        ...data,
      },
    });
  }, [updateUserAccount]);

  // get user accounts detail

  const [{ ...userAccountsDetail }, getUserAccountsDetail] = useAxios();

  const handleGetUserAccountsDetail = useCallback(async () => {
    await getUserAccountsDetail({
      method: "get",
      url: "/iam/v1/accounts/",
    });
  }, [getUserAccountsDetail]);

  // get user default account
  const [{ ...getDefaultAccount }, defaultAccount] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    },
  );

  const handleGetDefaultAccount = useCallback(async () => {
    try {
      return await defaultAccount({
        url: "/iam/v1/users/default_account/",
      });
    } catch (err) {
      //console.log(err);
      return err;
    }
  }, [defaultAccount]);

  // set user default account
  const [setDefaultAccount, setDefaultAccountState] = useState({
    loading: false,
    data: null,
    response: null,
    error: null,
  });

  const handleSetDefaultAccount = useCallback(async (accountID) => {
    if (!accountID) {
      return {};
    }

    setDefaultAccountState((currentState) => ({
      ...currentState,
      loading: true,
      error: null,
    }));

    try {
      const response = await postDefaultAccountRequest(accountID);
      setDefaultAccountState({
        loading: false,
        data: response?.data ?? null,
        response,
        error: null,
      });
      return response;
    } catch (err) {
      setDefaultAccountState({
        loading: false,
        data: err?.response?.data ?? null,
        response: err?.response ?? null,
        error: err,
      });
      return err;
    }
  }, []);
  const [{ ...unreadNotificationData }, getUnreadNotification] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    },
  );

  const handleGetUnreadNotification = useCallback(async (account_type, read = false) => {
    try {
      await getUnreadNotification({
        url: `/notify/v1/${
          account_type?.toLowerCase() === "personal" ? "" : account_type + "/"
        }notifications/`,
        params: {
          read: read,
        },
      });
    } catch (err) {
      //console.log(err);
    }
  }, [getUnreadNotification]);

  const [{ ...unreadNotificationPersonalData }, getUnreadNotificationPersonal] =
    useAxios(
      {
        method: "GET",
      },
      {
        manual: true,
      },
    );

  const handleGetUnreadNotificationPersonal = useCallback(async (read = false) => {
    try {
      await getUnreadNotificationPersonal({
        url: `/notify/v1/notifications/`,
        params: {
          read: read,
        },
      });
    } catch (err) {
      //console.log(err);
    }
  }, [getUnreadNotificationPersonal]);

  // general notification count
  const [{ ...generalNotificationCountData }, generalNotificationCount] =
    useAxios(
      {
        method: "GET",
      },
      {
        manual: true,
      },
    );

  const handleGeneralNotificationCount = useCallback(async (account_type = "") => {
    try {
      await generalNotificationCount({
        url: `/notify/v1/${
          account_type?.toLowerCase() === "personal" ? "" : account_type + "/"
        }notifications/general_notification_count/`,
      });
    } catch (err) {
      //console.log(err);
    }
  }, [generalNotificationCount]);

  // general notification count personal
  const [
    { ...generalNotificationCountPersonalData },
    generalNotificationCountPersonal,
  ] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    },
  );

  const handleGeneralNotificationCountPersonal = useCallback(async () => {
    try {
      await generalNotificationCountPersonal({
        url: `/notify/v1/notifications/general_notification_count/`,
      });
    } catch (err) {
      //console.log(err);
    }
  }, [generalNotificationCountPersonal]);

  //  Mark All Notification as Read Notification
  const [{ ...notificationMarkReadData }, getNotificationMarkRead] = useAxios(
    {
      method: "PUT",
    },
    {
      manual: true,
    },
  );

  const handleGetNotificationMarkRead = useCallback(async (account_type = "") => {
    try {
      await getNotificationMarkRead({
        url: `/notify/v1/${account_type}/notifications/mark_all_as_read/`,
      });
    } catch (err) {
      //console.log(err);
    }
  }, [getNotificationMarkRead]);

  //  Mark All Notification as Read Notification Personal acct
  const [
    { ...notificationMarkReadPersonalData },
    getNotificationMarkReadPersonal,
  ] = useAxios(
    {
      method: "PUT",
    },
    {
      manual: true,
    },
  );

  const handleGetNotificationMarkReadPersonal = useCallback(async () => {
    try {
      await getNotificationMarkReadPersonal({
        url: `/notify/v1/notifications/mark_all_as_read/`,
      });
    } catch (err) {
      //console.log(err);
    }
  }, [getNotificationMarkReadPersonal]);

  //Notification List
  const [{ ...notificationData }, getNotification] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    },
  );

  const handleGetNotification = useCallback(async (account_type = "", read) => {
    try {
      await getNotification({
        url: `/notify/v1/${account_type}/notifications/`,
        params: {
          read: read,
        },
      });
    } catch (err) {
      //console.log(err);
    }
  }, [getNotification]);

  // current plan
  const [{ ...userPlanData }, getUserPlan] = useAxios(
    {
      url: `/payment/v1/current_plan/`,
      method: "GET",
    },

    {
      manual: true,
    },
  );

  const handleGetUserPlan = useCallback(async () => {
    try {
      return await getUserPlan();
    } catch (err) {
      //console.log(err);
    }
  }, [getUserPlan]);

  //GET current subscription
  const [{ ...getCurrentSubscriptionData }, getCurrentSubscription] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    },
  );

  const handleCurrentSubscription = useCallback(async () => {
    try {
      return await getCurrentSubscription({
        url: `/payment/v1/current_subscription/`,
      });
    } catch (err) {
      //console.log(err);
    }
  }, [getCurrentSubscription]);

  const [{ ...getTotalMessagesCountData }, getTotalMessagesCount] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    },
  );

  const handleTotalMessagesCount = useCallback(async (
    account_type,
    enterprise_account_id,
  ) => {
    try {
      let apiUrl;

      if (account_type === "instructor") {
        // For instructor account type
        apiUrl = enterprise_account_id
          ? `/notify/v1/instructor/${enterprise_account_id}/chats/new_messages/` // Affiliate instructor
          : `/notify/v1/${account_type}/chats/new_messages/`; // Non-affiliate instructor
      } else if (account_type === "enterprise") {
        // For enterprise account type
        apiUrl = `/notify/v1/${account_type}/chats/new_messages/`; // Enterprise
      } else if (account_type === "personal") {
        apiUrl = `/notify/v1/chats/new_messages/`;
      } else {
      }
      await getTotalMessagesCount({
        url: apiUrl,
      });
    } catch (err) {
      console.log(err);
    }
  }, [getTotalMessagesCount]);

  const [{ ...getFileStorageSummaryData }, getFileStorageSummary] = useAxios(
    { method: "GET" },
    { manual: true },
  );
  const handleGetFileStorageSummary = useCallback(async (accountType) => {
    try {
      return await getFileStorageSummary({
        url: `/media/v1/${accountType}/filemanager/overview/`,
      });
    } catch (error) {
      console.log(error);
    }
  }, [getFileStorageSummary]);

  return {
    handleGetFileStorageSummary,
    getFileStorageSummaryData,
    handleGetUserDetails,
    userDetails,
    user: userDetails.data,
    getUserDetails,
    handleGetUserAccountsDetail,
    userAccountsDetail,
    handleGetDefaultAccount,
    getDefaultAccount,
    handleSetDefaultAccount,
    setDefaultAccount,
    unreadNotificationData,
    handleGetUnreadNotification,
    generalNotificationCountData,
    handleGeneralNotificationCount,
    notificationMarkReadData,
    handleGetNotificationMarkRead,
    notificationData,
    handleGetNotification,
    handleGetDefaultAffiliate,
    getDefaultAffiliateData,
    getAllAffiliateData,
    handleGetAllAffiliate,
    handleSetDefaultAffiliate,
    setDefaultAffiliateData,
    plan: userPlanData?.data,
    userPlanData,
    handleGetUserPlan,
    getCurrentSubscriptionData,
    handleCurrentSubscription,
    retrieveUserDetailsData,
    handleRetrieveUserDetails,
    updateUserAccountData,
    handleUpdateUserAccount,
    notificationMarkReadPersonalData,
    handleGetNotificationMarkReadPersonal,
    unreadNotificationPersonalData,
    handleGetUnreadNotificationPersonal,
    generalNotificationCountPersonalData,
    handleGeneralNotificationCountPersonal,
  };
};
export default useHeader;
