import { LocationCard } from './ui/LocationCard';
import { MonthTitle } from './ui/MonthTitle';
import { AddMonthButton } from './ui/AddMonthButton';
import { AddLocationButton } from './ui/AddLocationButton';
import { PageFooter } from './ui/PageFooter';
import { fetchAllLocations } from './lib/actions/locationActions';
import { formatCurrency } from './lib/formatStrings';
import { fetchAvailableYears } from './lib/actions/monthActions';
import { BillingLocation, YearMonth } from './lib/db-types';
import { formatYearMonth } from './lib/format';
import { FC, Fragment } from 'react';
import Pagination from './ui/Pagination';
import { PageHeader } from './ui/PageHeader';
import { Main } from './ui/Main';
import { MontlyExpensesCard } from './ui/MonthlyExpensesCard';

const getNextYearMonth = (yearMonth:YearMonth) => {
  const {year, month} = yearMonth;
  return({
    year: month===12 ? year+1 : year,
    month: month===12 ? 1 : month+1
  } as YearMonth);
}

export interface PageProps {
  searchParams?: {
    year?: string;
  };
}

const Page:FC<PageProps> = async ({ searchParams }) => {

  let availableYears: number[];

  try {
    availableYears = await fetchAvailableYears();
  } catch (error:any) {
    return (
      <main className="flex min-h-screen flex-col p-6 bg-base-300">
        <p className="text-center text-2xl text-red-500">{error.message}</p>
      </main>);
  }

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

  const [ latestYear ] = availableYears;
  const currentYear = Number(searchParams?.year) || availableYears[0];
  const locations = await fetchAllLocations(currentYear);

  // group locations by month
  const months = locations.reduce((acc, location) => {
    const {year, month} =  location.yearMonth;
    const key = `${year}-${month}`;

    const locationsInMonth = acc[key];

    if(locationsInMonth) {
      return({
        ...acc,
        [key]: {
          yearMonth: location.yearMonth,
          locations: [...locationsInMonth.locations, location],
          monthlyExpense: locationsInMonth.monthlyExpense + location.bills.reduce((acc, bill) => bill.paid ? acc + (bill.payedAmount ?? 0) : acc, 0)
        }
      })
    }

    return({
      ...acc,
      [key]: {
        yearMonth: location.yearMonth,
        locations: [location],
        monthlyExpense: location.bills.reduce((acc, bill) => bill.paid ? acc + (bill.payedAmount ?? 0) : acc, 0)
      }
    });
  }, {} as {[key:string]:{
    yearMonth: YearMonth,
    locations: BillingLocation[],
    monthlyExpense: number
  } });

 return (
    <Main>
        <AddMonthButton yearMonth={getNextYearMonth(locations[0].yearMonth)} />
        {
          Object.entries(months).map(([monthKey, { yearMonth, locations, monthlyExpense }], monthIx) => 
            <Fragment key={`month-${monthKey}`}>
              <MonthTitle yearMonth={yearMonth} />
              {
                locations.map((location, ix) => <LocationCard key={`location-${location._id}`} location={location} />)
              }
              {
                // show AddLocationButton as a last item in the first month
                monthIx === 0 ? <AddLocationButton yearMonth={yearMonth} /> : null
              }
              <MontlyExpensesCard monthlyExpense={monthlyExpense} />
            </Fragment>
          )
        }
        <div className="mt-5 flex w-full justify-center">
          <Pagination availableYears={availableYears} />
        </div>
    </Main>
  );
}

export default Page;