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 { isAuthErrorMessage } from '@/app/lib/auth';
import { fetchAllLocations } from './lib/actions/locationActions';
import { formatCurrency } from './lib/formatStrings';
import { fetchAvailableYears } from './lib/actions/monthActions';

const getNextYearMonth = (year:number, month:number) => {
  return({
    year: month<12 ? year+1 : year,
    month: month<12 ? month+1 : 1
  });
}

export const Page = async () => {

 const locations = await fetchAllLocations();
 const availableYearMonths = await fetchAvailableYears();

 if(isAuthErrorMessage(locations)) {
  return (
    <main className="flex min-h-screen flex-col p-6 bg-base-300">
      <p className="text-center text-2xl text-red-500">{locations.message}</p>
    </main>);
  }

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

  let monthlyExpense = 0;

 return (
    <main className="flex min-h-screen flex-col p-6 bg-base-300">
        <AddMonthButton {...getNextYearMonth(locations[0].year, locations[0].month)} />
        {
          locations.map((location, ix, array) => {

            const isFirstLocationInMonth = ix === 0 || location.year !== array[ix-1].year || location.month !== array[ix-1].month;
            const isLastLocationInMonth = location.year !== array[ix+1]?.year || location.month !== array[ix+1]?.month;
            const isLastLocationOfFirstMonth = isLastLocationInMonth && location.year === array[0].year && location.month === array[0].month;

            if(isFirstLocationInMonth) {
              monthlyExpense = 0;
            }

            monthlyExpense += location.bills.reduce((acc, bill) => acc + (bill.payedAmount ?? 0), 0);
            
            return (
              <>
                {
                  // show month title above the first LocationCard in the month
                  isFirstLocationInMonth ?
                    <MonthTitle key={`${location.year}-${location.month}`} year={location.year} month={location.month} /> : null
                }
                <LocationCard key={`${location._id}`} location={location} />
                {
                  // show AddLocationButton as a last item in the firts month
                  isLastLocationOfFirstMonth ?
                    <AddLocationButton key={`add-loc-${location.year}-${location.month}`} year={location.year} month={location.month} /> : null
                }
                {
                  isLastLocationInMonth && monthlyExpense>0 ?
                    <div className="card card-compact card-bordered max-w-[36em] bg-base-100 shadow-s my-1">
                        <span className="card-body self-center">
                          <p>
                            Total monthly expenditure: <strong>{ formatCurrency(monthlyExpense) }</strong>
                          </p>
                        </span>
                    </div> : null
                }
              </>
            )
          })
        }
        <PageFooter />
        { availableYearMonths.map(ym => <p key={`year-month-${ym}`}>{ym}</p>) }
    </main>
  );
}

export default Page;