import {
  Button,
  Checkbox,
  NumberInput,
  Paper,
  Title,
  Text,
} from "@mantine/core";
import { useForm } from "@mantine/form";
import { notifications } from "@mantine/notifications";
import { fetchHeaders } from "./fetch";
import React from "react";

type ProfileVerificationProps = Pick<
  UserProfile,
  "verify_mastodon_favorite" | "verify_delay"
> & { username: string };

type OrderVerificationForm = Pick<
  UserProfile,
  "verify_mastodon_favorite" | "verify_delay"
>;

export const ProfileVerification: React.FC<ProfileVerificationProps> = ({
  username,
  verify_mastodon_favorite,
  verify_delay,
}) => {
  const [loading, setLoading] = React.useState(false);
  const form = useForm<OrderVerificationForm>({
    mode: "uncontrolled",
    initialValues: {
      verify_mastodon_favorite,
      verify_delay,
    },
    validate: {
      verify_delay: (value: number, values: OrderVerificationForm) => {
        console.log("oh boy", values.verify_mastodon_favorite, value);
        return !values.verify_mastodon_favorite || value
          ? null
          : "You must set a verification delay";
      },
    },
  });

  const handleSubmit = React.useCallback(
    form.onSubmit((values) => {
      setLoading(true);
      fetch(`/api/subs/${username}`, {
        method: "POST",
        headers: fetchHeaders(),
        body: JSON.stringify(values),
      })
        .then((response) => {
          if (response.ok) {
            notifications.show({
              title: "Success",
              message: "Your preferences have been saved",
              color: "green",
            });
          } else {
            notifications.show({
              title: "Error",
              message: "There was a problem saving your preferences",
              color: "red",
            });
          }
        })
        .finally(() => {
          setLoading(false);
        });
    }),
    [],
  );

  return (
    <Paper bg="gray.1">
      <form onSubmit={handleSubmit}>
        <Title order={4} mb="md">
          Order Verification
        </Title>
        <Checkbox
          {...form.getInputProps("verify_mastodon_favorite", {
            type: "checkbox",
          })}
          label="Posts must be Favorited by a dom or tagged account"
          mb="md"
        />
        <NumberInput
          {...form.getInputProps("verify_delay")}
          label="Verification Delay"
          description="Hours to wait after order is due to verify post"
          min={1}
          max={168}
          rightSection={<Text mr="xl">hours</Text>}
        />
        <Button type="submit" loading={loading} mt="md">
          Save
        </Button>
      </form>
    </Paper>
  );
};
