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 { Location } from './lib/db-types';

export const Page = async () => {

 const client = await clientPromise;
 const db = client.db("rezije");

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

 return (
    <main className="flex min-h-screen flex-col p-6 bg-base-300">
        <p>https://tailwindcss.com/docs/font-weight</p>
        <p>https://heroicons.com/</p>

        <AddMonthButton />
        {
          locations.map((location, ix, array) => {
            
            return (
              <>
                {
                  location.yearMonth !== array[0].yearMonth && location.yearMonth !== array[ix-1].yearMonth ? <AddLocationButton /> : null
                }
                {
                  // show month title if it's the first location in the month
                  ix === 0 || location.yearMonth !== array[ix-1].yearMonth ? <MonthTitle yearMonth={location.yearMonth} /> : null
                }
                <LocationCard key={`${location._id}`} location={location} />
              </>
            )
          })
        }
    </main>
  );
}

export default Page;