import {
  Alert,
  AlertIcon,
  Button,
  Table,
  TableCaption,
  TableContainer,
  Tbody,
  Td,
  Th,
  Thead,
  Tr,
} from "@chakra-ui/react";
import { useLoaderData } from "@remix-run/react";

export async function loader({ context }: { context: RequestContext }) {
  const now = new Date();
  let month = now.getUTCMonth() + 1;
  let year = now.getUTCFullYear();

  if (month - 1 === 0) {
    month = 12;
    year--;
  }

  const data = await context.env.D1.prepare(
    "SELECT day, details, id FROM events WHERE approved = 1 AND month = ? AND year = ? AND (performed_at IS NULL OR reached_minimum_player_count = 0 OR answered_at IS NULL);",
  )
    .bind(month, year)
    .all();

  return {
    events: data.results as Record<string, string | number>[],
    past_cutoff: now.getUTCDate() > 7,
  };
}

export default function () {
  const { events, past_cutoff } = useLoaderData<typeof loader>();

  function getStatus(event: { [k: string]: string | number }) {
    if (!event.performed_at) return "Approved";
    if (event.type === "rotw" && event.answered_at) return "Solved";
    if (event.type === "gamenight" && event.areached_minimum_player_count)
      return "Certified";

    return "Completed";
  }

  return (
    <>
      <Alert display={past_cutoff ? undefined : "none"} status="warning">
        <AlertIcon />
        The cutoff period for retroactively actioning events has passed.
      </Alert>
      <TableContainer>
        <Table variant="simple">
          <TableCaption>
            Events that are not denied or left pending which need to be actioned
          </TableCaption>
          <Thead>
            <Tr>
              <Th>Day</Th>
              <Th>Details</Th>
              <Th>Current Status</Th>
              <Th>Action</Th>
            </Tr>
          </Thead>
          <Tbody>
            {events.map((event) => (
              <Tr>
                <Td>{event.day}</Td>
                <Td>{event.details}</Td>
                <Td>{getStatus(event)}</Td>
                <Td>
                  <Button>Action Menu</Button>
                </Td>
              </Tr>
            ))}
          </Tbody>
        </Table>
      </TableContainer>
    </>
  );
}
