import { LocationCard } from './ui/LocationCard';
import { MonthTitle } from './ui/MonthTitle';
import { AddMonthButton } from './ui/AddMonthButton';
import { AddLocationButton } from './ui/AddLocationButton';
import clientPromise from './lib/mongodb';
import { BillingLocation } from './lib/db-types';
import { PageFooter } from './ui/PageFooter';
import { auth } from '@/app/lib/auth.google';
import { redirect } from 'next/navigation';

const getNextYearMonth = (yearMonth:number) => {
  return(yearMonth % 100 === 12 ? yearMonth + 89 : yearMonth + 1);
}

export const Page = async () => {

  const session = await auth();

 const client = await clientPromise;
 const db = client.db("rezije");
 
 const locations = await db.collection<BillingLocation>("lokacije")
    .find({})
    .sort({ yearMonth: -1, name: 1 }) // sort by yearMonth descending
    .limit(20)
    .toArray();

  // if the database is in it's initial state, show the add location button for the current month
  if(locations.length === 0) {
    const currentYearMonth = new Date().getFullYear() * 100 + new Date().getMonth() + 1;
    return (
      <main className="flex min-h-screen flex-col p-6 bg-base-300">
        <MonthTitle yearMonth={currentYearMonth} />
        <AddLocationButton yyyymm={currentYearMonth} />
        <PageFooter />
      </main>
    );
  }

 return (
    <main className="flex min-h-screen flex-col p-6 bg-base-300">
        <AddMonthButton nextYearMonth={getNextYearMonth(locations[0].yearMonth)} />
        {
          locations.map((location, ix, array) => {
            
            return (
              <>
                {
                  // show month title above the first LocationCard in the month
                  ix === 0 || location.yearMonth !== array[ix-1].yearMonth ?
                    <MonthTitle key={location.yearMonth} yearMonth={location.yearMonth} /> : null
                }
                <LocationCard key={`${location._id}`} location={location} />
                {
                  // show AddLocationButton as a last item in the firts month
                  location.yearMonth === array[0].yearMonth && location.yearMonth !== array[ix+1]?.yearMonth ?
                    <AddLocationButton key={`add-loc-${location.yearMonth}`} yyyymm={location.yearMonth} /> : null
                }
              </>
            )
          })
        }
        <PageFooter />
        <ul>
          <li>session.expires = { session?.expires }</li>
          <li>session.user.id = { session?.user?.id }</li>
          <li>session.user.email = { session?.user?.email }</li>
          <li>session.user.name = { session?.user?.name }</li>
          <li>session.user.image = { session?.user?.image }</li>
        </ul>
    </main>
  );
}

export default Page;