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

export async function loader({ context }: { context: RequestContext }) {
  const { current_user: currentUser } = context.data;

  if (!currentUser)
    throw new Response(null, {
      status: 401,
    });

  const permissionGroups = {
    DM: [1 << 11],
    ET: [1 << 4, 1 << 12],
    FM: [1 << 7],
    WM: [1 << 11],
  };

  const searchDepartments = [];

  for (const department of Object.keys(permissionGroups)) {
    if (currentUser.permissions & (1 << 0)) searchDepartments.push(department);
    else if (
      permissionGroups[department as "DM" | "ET" | "FM" | "WM"].find(
        (p) => currentUser.permissions & p,
      )
    )
      searchDepartments.push(department);
  }

  if (!searchDepartments.length)
    throw new Response(null, {
      status: 403,
    });

  const today = new Date().toISOString().split("T").at(0);
  const { results } = await context.env.D1.prepare(
    "SELECT decisions, end, start, user FROM inactivity_notices WHERE start <= ?1 AND date(end, '+30 days') <= ?1; ",
  )
    .bind(today)
    .all();

  for (let i = 0; i < results.length; i++)
    results[i].user = JSON.parse(results[i].user as string);

  return results.filter((row) => {
    const decisionValues = Object.values(
      row.decisions as { [k: string]: boolean },
    );

    return decisionValues.find((d) => d);
  }) as unknown as {
    decisions: { [k: string]: boolean };
    end: string;
    start: string;
    user: { email: string; id: string; username: string };
  }[];
}

export default function () {
  const data = useLoaderData<typeof loader>();

  return (
    <Container maxW="container.lg">
      <Heading pb="32px">Current Inactivity Notices</Heading>
      <TableContainer>
        <Table variant="simple">
          <TableCaption>
            All recent inactivity notices (current and last 30 days)
          </TableCaption>
          <Thead>
            <Tr>Name</Tr>
            <Tr>User ID</Tr>
            <Tr>Start Date</Tr>
            <Tr>End Date</Tr>
            <Tr>View More</Tr>
          </Thead>
          <Tbody>
            {data.map((row) => (
              <Tr>
                <Td>{row.user.username}</Td>
                <Td>{row.user.id}</Td>
                <Td>{row.start}</Td>
                <Td>{row.end}</Td>
                <Button>View More</Button>
              </Tr>
            ))}
          </Tbody>
        </Table>
      </TableContainer>
    </Container>
  );
}
