import {
  Container,
  Title,
  Card,
  Text,
  Button,
  Flex,
  Badge,
} from "@mantine/core";
import { TimeValue } from "@mantine/dates";
import { IconPencil, IconPlus } from "@tabler/icons-react";
import React from "react";
import { Params, useLoaderData, useParams, useNavigate } from "react-router";

export const subOrderSetsLoader = async ({
  params: { username },
}: {
  params: Params<string>;
}) => fetch(`/api/subs/${username}/sets`).then((response) => response.json());

const NavigateButton: React.FC<{
  children: React.ReactNode;
  to: string;
}> = ({ children, to }) => {
  const navigate = useNavigate();

  const handleClick = React.useCallback(() => {
    navigate(to);
  }, [to]);

  return (
    <Button onClick={handleClick} px="md" w="auto">
      {children}
    </Button>
  );
};

export const SubOrderSets: React.FC = () => {
  const { username: sub_username } = useParams();
  const orderSets = useLoaderData<
    (Pick<
      OrderSet,
      "id" | "name" | "scheduled" | "time" | "weekends" | "weekdays" | "orders"
    > & {
      orders: Pick<OrderSetOrder, "id" | "name">[];
    })[]
  >();

  return (
    <Container>
      <Title order={1} mb="lg">
        Order Sets for {sub_username}
      </Title>
      <Flex gap="md" wrap="wrap">
        {orderSets
          ? orderSets.map(
              ({ id, name, scheduled, orders, time, weekdays, weekends }) => (
                <Card
                  key={id}
                  shadow="sm"
                  padding="lg"
                  radius="md"
                  withBorder
                  bg="gray.2"
                  w="400px"
                >
                  <Flex direction="column" gap="md">
                    <Title order={4}>{name}</Title>
                    {scheduled ? (
                      <Flex gap="md" align="center">
                        <Text>
                          Scheduled: <TimeValue value={time} format="12h" />
                        </Text>
                        {weekdays ? <Badge color="blue">Weekdays</Badge> : null}
                        {weekends ? <Badge color="blue">Weekends</Badge> : null}
                      </Flex>
                    ) : null}
                    <Text mb="md">Orders: {orders.length}</Text>
                  </Flex>
                  <Flex justify="end">
                    <NavigateButton
                      to={`/dashboard/subs/${sub_username}/${id}`}
                    >
                      <IconPencil style={{ marginRight: "0.5rem" }} />
                      Edit
                    </NavigateButton>
                  </Flex>
                </Card>
              ),
            )
          : null}
      </Flex>
      <NavigateButton to={`/dashboard/subs/${sub_username}/new`}>
        <IconPlus style={{ marginRight: "0.5rem" }} />
        New
      </NavigateButton>
    </Container>
  );
};
