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

export async function loader({ context }: { context: RequestContext }) {
  if (!context.data.current_user)
    throw new Response(null, {
      status: 401,
    });

  if (
    ![1 << 3, 1 << 4, 1 << 12].find(
      (p) => context.data.current_user.permissions & p,
    )
  )
    throw new Response(null, {
      status: 403,
    });

  const etData = await context.env.D1.prepare(
    "SELECT id, name, points, roblox_id FROM et_members;",
  ).all();

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

  return etData.results as { [k: string]: any }[];
}

export default function () {
  async function removeMember(id: string) {
    await fetch("/api/events-team/team-members/user", {
      body: JSON.stringify({ id }),
      headers: {
        "content-type": "application/json",
      },
      method: "DELETE",
    });

    setMemberData(memberData.filter((member) => member.id !== id));
  }

  const [realtimePoints, setRealtimePoints] = useState(0);
  const [memberData, setMemberData] = useState(useLoaderData<typeof loader>());

  return (
    <Container maxW="container.lg">
      <Heading>Events Team Members</Heading>
      <TableContainer pt="16px">
        <Table variant="simple">
          <TableCaption>
            Points are updated at the end of the month
          </TableCaption>
          <Thead>
            <Tr>
              <Th>Discord ID</Th>
              <Th>Name</Th>
              <Th>Roblox ID</Th>
              <Th>Points</Th>
              <Th>Remove</Th>
            </Tr>
          </Thead>
          <Tbody>
            {memberData.map((member) => (
              <Tr>
                <Td>{member.id}</Td>
                <Td>{member.name}</Td>
                <Td>{member.roblox_id}</Td>
                <Td>{member.points}</Td>
                <Td>
                  <Link onClick={async () => removeMember(member.id)}>
                    Remove
                  </Link>
                </Td>
              </Tr>
            ))}
          </Tbody>
        </Table>
      </TableContainer>
    </Container>
  );
}
