import { isValidDate } from '@/lib/utils';
import { format } from 'date-fns';
import { redirect } from 'next/navigation';
import { Suspense } from 'react';
import MessageGridServer from '../../components/internal/MessageGridServer';
import { sessionUser } from '@/auth';
import MessageFilter from '@/components/internal/MessageFilter';
import { MessageFilterParams } from '@/lib/types';
import { IconLoading } from '@/components/ui/Icons';
import Loading from '@/components/ui/Loading';

export interface pageProps {
  searchParams?: { [key: string]: string | string[] | undefined };
}

export default async function page({ searchParams }: pageProps) {
  const { isAdmin } = await sessionUser();
  if (!isAdmin) {
    redirect('/');
  }

  // Default filter is today's date
  if (
    !searchParams ||
    !searchParams?.date ||
    !isValidDate(searchParams?.date as string)
  ) {
    const today = new Date();
    // default to today
    redirect(`/internal?date=${format(today, 'yyyy-MM-dd')}`);
  }

  const messageFilter = Object.entries(searchParams).reduce((acc, entry) => {
    switch (entry[0]) {
      case 'date':
        return { ...acc, date: entry[1] as string };
      case 'includeExamples':
        return { ...acc, includeExamples: entry[1] === 'true' };
      default:
        return acc;
    }
  }, {} as MessageFilterParams);

  return (
    <div className="w-[1600px] max-w-full mx-auto flex flex-col space-y-4 items-center">
      <MessageFilter messageFilter={messageFilter} />
      <Suspense
        // https://stackoverflow.com/questions/76644147/suspense-fallback-is-not-showing-in-nextjs-13-when-navigate-by-userouter
        key={JSON.stringify(searchParams)}
        fallback={
          <div className="h-screen w-screen flex justify-center items-center">
            <Loading />
          </div>
        }
      >
        <MessageGridServer messageFilter={messageFilter} />
      </Suspense>
    </div>
  );
}
