import {
  Alert,
  AlertDescription,
  AlertIcon,
  AlertTitle,
  Button,
  Container,
  Heading,
  HStack,
  Input,
  Radio,
  RadioGroup,
  Textarea,
  useToast,
} from "@chakra-ui/react";
import { useEffect, useState } from "react";
import Success from "../../components/Success.js";
import { useLoaderData } from "@remix-run/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 now = new Date();
  const preBookedEvents = await context.data.prisma.event.count({
    where: {
      created_by: context.data.current_user.id,
      day: {
        gte: now.getUTCDate(),
      },
      month: now.getUTCMonth() + 1,
      year: now.getUTCFullYear(),
    },
  });

  return preBookedEvents > 3;
}

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

  const toast = useToast();
  const currentDate = new Date();
  const currentMonth = currentDate.getUTCMonth() + 1;
  const [datePickerMax, setDatePickerMax] = useState("");
  const [datePickerMin, setDatePickerMin] = useState("");
  const [eventDay, setEventDay] = useState("0");
  const [eventDetails, setEventDetails] = useState("");
  const [eventType, setEventType] = useState("");
  const [riddleAnswer, setRiddleAnswer] = useState("");
  const [submitSuccess, setSubmitSuccess] = useState(false);
  const [disableSubmit, setDisableSubmit] = useState(exceededMaxBookings);

  useEffect(() => {
    setDatePickerMin(`${new Date().toISOString().split("T").at(0)}`);
    currentDate.setUTCMonth(currentMonth);
    currentDate.setUTCDate(0);
    setDatePickerMax(`${currentDate.toISOString().split("T").at(0)}`);
  }, []);

  async function submit() {
    setDisableSubmit(true);
    let eventResp: Response;

    try {
      eventResp = await fetch("/api/events-team/events/new", {
        body: JSON.stringify({
          answer: riddleAnswer || undefined,
          day: parseInt(eventDay),
          details: eventDetails,
          type: eventType,
        }),
        headers: {
          "content-type": "application/json",
        },
        method: "POST",
      });
    } catch {
      setDisableSubmit(false);
      toast({
        description: "Please check your internet and try again",
        isClosable: true,
        status: "error",
        title: "Unknown error",
      });

      return;
    }

    if (!eventResp.ok) {
      let errorMessage = "Unknown error";

      try {
        errorMessage = ((await eventResp.json()) as { error: string }).error;
      } catch {}

      setDisableSubmit(false);
      toast({
        description: errorMessage,
        isClosable: true,
        status: "error",
        title: "Oops!",
      });

      return;
    }

    setSubmitSuccess(true);
    await new Promise((r) => setTimeout(r, 7500));
    location.assign("/events-team");
  }

  return submitSuccess ? (
    <Success
      heading="Event Booked"
      message="You will be notified when it is approved"
    />
  ) : (
    <Container maxW="container.md">
      <Alert display={exceededMaxBookings ? undefined : "none"} status="error">
        <AlertIcon />
        <AlertTitle>Max pre-bookings exceeded!</AlertTitle>
        <AlertDescription>
          You cannot pre-book more than three events. Please wait until you
          complete an event before trying again.
        </AlertDescription>
      </Alert>
      <Heading pb="32px">Book an Event</Heading>
      <Heading mb="8px" size="md">
        Event Type
      </Heading>
      <RadioGroup onChange={setEventType} value={eventType}>
        <HStack>
          <Radio value="fotd">FoTD</Radio>
          <Radio value="gamenight">Gamenight</Radio>
          <Radio value="qotd">QoTD</Radio>
          <Radio value="rotw">RoTW</Radio>
        </HStack>
      </RadioGroup>
      <br />
      <Heading pb="8px" pt="16px" size="md">
        Event Date
      </Heading>
      <input
        max={datePickerMax}
        min={datePickerMin}
        onChange={(e) => setEventDay(e.target.value.split("-")[2])}
        type="date"
      />
      <Heading mb="8px" pt="16px" size="md">
        Event Details
      </Heading>
      <Textarea
        onChange={(e) => setEventDetails(e.target.value)}
        placeholder="For gamenights, provide information about the game and the link. For all other events, type out the fact/question/riddle."
      />
      <Heading
        display={eventType === "rotw" ? undefined : "none"}
        mb="8px"
        pt="16px"
        size="md"
      >
        Riddle Answer
      </Heading>
      <Input
        display={eventType === "rotw" ? undefined : "none"}
        onChange={(e) => setRiddleAnswer(e.target.value)}
        placeholder="Riddle answer"
      />
      <Button
        disabled={disableSubmit}
        mt="16px"
        onClick={async () => await submit()}
      >
        Book
      </Button>
    </Container>
  );
}
