import { documentId, where } from "firebase/firestore";
import { useState } from "react";
import FirebaseQuery from "../../firebase/firebaseQuery";
import { UserData } from "../../typeDefinitions";

export function useReferrals({user}: {user: UserData}){
    const firebaseQuery = new FirebaseQuery();
    const [showNameConsent, setShowNameConsent] = useState<boolean>(user?.shareNameWithReferralLeaderboardConsent === undefined ? true : false);

    const getReferralCode = async (fiveLetterWords: string[]): Promise<string> => {
      var potentialWord = fiveLetterWords[Math.floor(Math.random()*fiveLetterWords.length)];
      const existingReferral = await firebaseQuery.getDocsWhere("referrals", where(documentId(), "==", potentialWord));

      if (Object.keys(existingReferral || {}).length > 0) {
          return await getReferralCode(fiveLetterWords);
      }

      await firebaseQuery.set(["referrals", potentialWord], {
          name: user?.id,
          expiry: new Date(2040,10,30),
          volume: 1000,
          product: "students"

      }).then(() => {
        if (!user) return;
        firebaseQuery.update(["users", user.id], {
          referralCode: potentialWord
        })
        //dispatch(updateUser({userId: user.id, attributes: {referralCode: potentialWord}}))
    //    dispatch(setUser((state: UserData) => ({...state, referralCode: potentialWord})))
      })

      return potentialWord;
    }

    const consent = async (consent: boolean) => {
      if (!user) return

      try {
        await firebaseQuery.update(["users", user.id], {
            shareNameWithReferralLeaderboardConsent: consent,
            shareNameWithReferralLeaderboardConsentDate: (new Date()).toISOString()
        })
        // dispatch(updateUser({userId: user.id, attributes: { 
        //   shareNameWithReferralLeaderboardConsent: consent,
        //   shareNameWithReferralLeaderboardConsentDate: (new Date()).toISOString()}
        // }))
      }
       catch(error) {
        console.log(error)
      }
      setShowNameConsent(false);
  }

    return ({...{getReferralCode, showNameConsent, setShowNameConsent, consent}})
    
}