import React, { useContext, createContext, useEffect, useState } from "react";

import firebase from "../config/firebase";
import { useUserData } from "./UserDataProvider";

export const PremiumContext = createContext();

export default ({ children }) => {
  const { currentUID } = useUserData();

  const [subscriptions, setSubscriptions] = useState(null);

  const subscriptionType = subscriptions?.length > 0 ? "PREMIUM" : "FREE";
  const isPaying = subscriptionType !== "FREE";

  useEffect(() => {
    if (currentUID) {
      getPremiumStatus();
    }
  }, [currentUID]);

  const getPremiumStatus = async () => {
    try {
      const { data } = await firebase
        .functions()
        .httpsCallable("payment-getPremiumStatus")({
        userID: currentUID,
      });

      if (data?.subscriptions?.length) {
        setSubscriptions(
          (data.subscriptions || [])?.filter((sub) => sub.status === "active")
        );
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <PremiumContext.Provider
      value={{
        getPremiumStatus,

        subscriptionType,
        subscriptions,

        isPaying,
      }}
    >
      {children}
    </PremiumContext.Provider>
  );
};

export const usePremium = () => useContext(PremiumContext);
