import { Button, Card, Container, Heading, VStack } from "@chakra-ui/react";
import { useLoaderData } from "@remix-run/react";

export async function loader({ context }: { context: RequestContext }) {
  const state = crypto.randomUUID().replace(/-/g, "");
  const url = new URL(context.request.url);
  url.pathname = "/api/data-requests/session";

  await context.env.DATA.put(
    `rbxstate_${state}`,
    context.request.headers.get("cf-connecting-ip") ?? "",
    {
      expirationTtl: 300,
    },
  );

  return {
    client_id: context.env.ROBLOX_OAUTH_CLIENT_ID,
    state,
    url: encodeURIComponent(url.href),
  };
}

export default function () {
  const { client_id, state, url } = useLoaderData<typeof loader>();

  return (
    <Container pt="16vh">
      <Card borderRadius="32px" p="4vh">
        <VStack alignContent="center" gap="2vh">
          <Heading>Log in to Car Crushers</Heading>
          <br />
          <Button
            as="a"
            borderRadius="24px"
            colorScheme="blue"
            href={`https://apis.roblox.com/oauth/v1/authorize?client_id=${client_id}&redirect_uri=${url}&response_type=code&state=${state}`}
          >
            Log in with Roblox
          </Button>
        </VStack>
      </Card>
    </Container>
  );
}
