import { useState, useEffect } from 'react'
import { dateToString, convertDate } from '../../../firebase/util'
import { executeCallable } from '../../../firebase/firebase'
import { UserData, StudentPlacementData } from '../../../typeDefinitions'
import { arrayUnion } from 'firebase/firestore'
import FirebaseQuery from '../../../firebase/firebaseQuery'

export function useUserFunctions({user}: {user: UserData}) {
const firebaseQuery = new FirebaseQuery()

  const update = async (attributes: any) => {
    if (!user) return
    firebaseQuery.update(["users", user.id], {attributes})
   // dispatch(updateUser({userId: user.id, attributes: attributes}))
  }

  return ({...{update}});
}

export function useActivationCode({user}: {user: UserData}){
  const [code, setCode] = useState<string>("");
  const [newCodeSent,  setNewCodeSent] = useState<boolean|undefined>(false);
  const [timer, setTimer] = useState<number>(30);
  const firebaseQuery = new FirebaseQuery()

  useEffect(() => {
      setInterval(() => {
          setTimer((t) => t > 0 ? t-1 : t);
      }, 1000)
  }, [])

  const submitCode = async (skip?: boolean) => {
      if (!user) return;

      if (skip || (parseInt(code) === user.activationCode)) {
          firebaseQuery.update(["users", user.id], {activated: dateToString(new Date()), status: "active"})
          //dispatch(updateUser({userId: user.id, attributes: {activated: dateToString(new Date()), status: "active"}}))
      }
  }

  const resendCode = async () => {
      setNewCodeSent(undefined)
      await executeCallable("registration-resendCode", {});
      setNewCodeSent(true);
      setTimer(30)
  }

  return ({...{code, setCode, submitCode, resendCode, newCodeSent, timer}})
  
}

export function useContactProviderConsent({user}: {user: UserData}){
    const [active, setActive] = useState<boolean>(false);
    const firebaseQuery = new FirebaseQuery()

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

        try {
            await firebaseQuery.update(["users", user.id], {
            contactProviderConsent: consent,
                 contactProviderConsentDate: (new Date()).toISOString()
            })
            // dispatch(updateUser({userId: user.id, attributes: {
            //     contactProviderConsent: consent, 
            //     contactProviderConsentDate: (new Date()).toISOString()}
            // }))

            setActive(false);
        }

        catch(error) {
            console.log(error)
        }
    }
    return ({...{active, setActive, consent}})
    
}


export function useGuidance({user}: {user: UserData}){
    const firebaseQuery = new FirebaseQuery()

  const updateUserTutorials = () => {
      if (!user) return
      try {
          firebaseQuery.update(["users", user.id], {dismissedTutorials: arrayUnion("studentIntro")});
         // dispatch(updateUser({userId: user.id, attributes: {dismissedTutorials: arrayUnion("studentIntro")}}))
      }

      catch (error) {
          console.log(error)
      }
  }

  return ({...{updateUserTutorials}})
}

export function useStudents(user: UserData | null){
    const firebaseQuery = new FirebaseQuery()

  useEffect(() => {
      if (!user?.id) return;
    firebaseQuery.update(["users", user?.id], {lastAccessed: convertDate(new Date(), "dbstring")})
      //dispatch(updateUser({userId: user.id, attributes: {lastAccessed: convertDate(new Date(), "dbstring")}}))

      if (!user?.phone && user?.status === "inactive") {
         firebaseQuery.update(["users", user.id], {status: "active"})
         // dispatch(updateUser({userId: user.id, attributes: {status: "active"}}))
      };
  }, []);


}

export function useStudentData(placement: StudentPlacementData, student: UserData){
  const firebaseQuery = new FirebaseQuery();
  const [studentData, setStudentData] = useState<UserData | undefined>();

  
  useEffect(() => {
      const getStudentData = async () => {
          return student ? student : (await firebaseQuery.getDocData(["users", placement.uid])) as UserData;
      };
      getStudentData().then((data) => {
          setStudentData(data);
      });
  }, []);


return ({...{studentData}})

}