import {
  Box,
  Card,
  CardBody,
  CardHeader,
  Container,
  Heading,
  Link,
  Stack,
  StackDivider,
  Text,
  VStack,
} from "@chakra-ui/react";
import { useLoaderData } from "@remix-run/react";
import { type ReactNode } from "react";

export async function loader({ context }: { context: RequestContext }) {
  const now = new Date();
  const monthEventList = await context.env.D1.prepare(
    "SELECT * FROM events WHERE month = ? AND year = ?;",
  )
    .bind(now.getUTCMonth() + 1, now.getUTCFullYear())
    .all();

  if (monthEventList.error)
    throw new Response(null, {
      status: 500,
    });

  return monthEventList.results;
}

export default function () {
  const data = useLoaderData<typeof loader>();
  const daysInThisMonth = new Date().setUTCDate(0);
  const dayCards: ReactNode[] = [];

  for (let i = 0; i < daysInThisMonth; i++) {
    const dayData: { [k: string]: any }[] = data.filter(
      (row) => row.day === i + 1,
    );

    if (!dayData.length) continue;

    const fotd = dayData.find((d) => d.type === "fotd");
    const gamenight = dayData.find((d) => d.type === "gamenight");
    const qotd = dayData.find((d) => d.type === "qotd");

    const dayCard = (
      <Card width="100%">
        <CardHeader>
          <Heading size="md">
            {new Date(
              dayData[0].year,
              dayData[0].month,
              dayData[0].day,
            ).toDateString()}
          </Heading>
        </CardHeader>
        <CardBody>
          <Stack divider={<StackDivider />} spacing={4}>
            <Box>
              <Heading size="xs">FACT OF THE DAY</Heading>
              {fotd ? <Text pt="2">Booked</Text> : <Link>Book</Link>}
            </Box>
            <Box>
              <Heading size="xs">GAMENIGHT</Heading>
              {gamenight ? <Text pt="2">Booked</Text> : <Link>Book</Link>}
            </Box>
            <Box>
              <Heading size="xs">QUESTION OF THE DAY</Heading>
              {qotd ? <Text pt="2">Booked</Text> : <Link>Book</Link>}
            </Box>
          </Stack>
        </CardBody>
      </Card>
    );

    dayCards.push(dayCard);
  }

  return (
    <Container maxW="container.lg">
      <VStack>{dayCards}</VStack>
    </Container>
  );
}
