import {useState} from "react"
import FirebaseQuery from "../../firebase/firebaseQuery"
import {where} from "firebase/firestore"
import {StudentPlacementData, UserData} from "../../typeDefinitions"
import {useAppDispatch} from "../../reduxHooks"
import {updateUpcomingStudentPlacement} from "../placements/studentPlacements/upcomingStudentPlacementsSlice"
import { updateCompletedStudentPlacement } from "../placements/studentPlacements/completedStudentPlacementsSlice"

export function useAnalyticsCard({user}: {user: UserData}){
    const [total, setTotal] = useState<number>();
    const [completed, setCompleted] = useState<number>();
    const [_, setPlacementsWithoutAnalytics] = useState<{[key:string]: StudentPlacementData}>();
    const firebaseQuery = new FirebaseQuery();

    const fetchAnalyticsCardDetails = async () => {
        try  {
            setTotal(await firebaseQuery.getCount("placements", [where("uid", "==", user.id)]))
            setCompleted(await firebaseQuery.getCount("placements", [where("uid", "==", user.id), where("completed", "==", true)]))
            setPlacementsWithoutAnalytics(await firebaseQuery.getDocsWhere("placements", [where("uid", "==", user.id)]) as {[key:string]: StudentPlacementData});
            
        } catch(error) {
            console.log(error)
        }
      
    }


    return ({...{total, completed, fetchAnalyticsCardDetails}})
}

export function useAnalyticsViews(user: UserData | null){
    const [placementsWithoutAnalytics, setPlacementsWithoutAnalytics] = useState<{[key:string]: StudentPlacementData}>();
    const firebaseQuery = new FirebaseQuery();

    const fetchAnalyticsViews = async () => {
        try {
            const docs = await firebaseQuery.getDocsWhere("placements", [where("uid", "==", user?.id)])
            const p = Object.fromEntries(Object.entries(docs as {[key:string]: StudentPlacementData}).filter(([_, v]) => (!v.units || !v.personalAnalytics)))
            setPlacementsWithoutAnalytics(p)

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

    return ({...{placementsWithoutAnalytics, fetchAnalyticsViews}})

}

export function useReviewPlacementItem(id: string, onComplete: () => void){
    const [analytics, setAnalytics] = useState<{units: string|undefined, personalAnalytics: string[]|undefined}>();
    const dispatch = useAppDispatch()

    const submitPlacementData = async (type: "upcoming" | "completed") => {
        if (!analytics?.units) return;
       // await firebaseQuery.update(["placements", id], analytics);
        type === "upcoming" ? dispatch(updateUpcomingStudentPlacement({placementId: id, attributes: analytics})) : dispatch(updateCompletedStudentPlacement({placementId: id, attributes: analytics}))
        onComplete()
    }

    return ({...{analytics, setAnalytics, submitPlacementData}})

}