"use client"
import React, { useEffect, useState } from 'react'
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import ScheduleList from './_components/ScheduleList'
import { collection, getDocs, getFirestore, query, where } from 'firebase/firestore'
import { app } from '@/config/FirebaseConfig'
import { useKindeBrowserClient } from '@kinde-oss/kinde-auth-nextjs'
import { format } from 'date-fns'


const ScheduleMeeting = () => {
    const [meetingList, setMeetingList] = useState([]);

    const {user} = useKindeBrowserClient();
    const db = getFirestore(app);

    const getSchedule = async () => {
        setMeetingList([])
        const q = query(collection(db, 'ScheduleMeeting'), where('businessEmail', '==', user.email))
        const querySnapshot = await getDocs(q);

        querySnapshot.forEach(doc => {
            console.log(doc.data());
            setMeetingList(prev => [...prev, doc.data()])
        })
    }

    //filter meeting
    const filterMeetingList = (type) => {
        if(type == 'upcoming'){
            return meetingList.filter(item => item.formatedTimeStamp >= format(new Date(), 't'))
        } else{
            return meetingList.filter(item => item.formatedTimeStamp < format(new Date(), 't'))
        }
    }

    useEffect(() => {
        user && getSchedule()
    }, [user])


  return (
    <div className='px-5'>
        <p className='font-semibold text-xl mb-5'>Schedule Meeting</p><hr/>
        <Tabs defaultValue="upcoming" className="w-[400px] mt-5">
            <TabsList>
                <TabsTrigger value="upcoming">Upcoming</TabsTrigger>
                <TabsTrigger value="history">Meeting History</TabsTrigger>
            </TabsList>
            <TabsContent value="upcoming">
                <ScheduleList meetingList={filterMeetingList('upcoming')}/>
            </TabsContent>
            <TabsContent value="history">
                <ScheduleList meetingList={filterMeetingList('history')}/>
            </TabsContent>
        </Tabs>
    </div>
  )
}

export default ScheduleMeeting