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

type ProfilePermissionsProps = Pick<
  UserProfile,
  | "permission_orders_pools_view"
  | "permission_orders_pools_details"
  | "permission_orders_pools_edit"
> & { username: string };

type ProfilePermissionsForm = Pick<
  UserProfile,
  | "permission_orders_pools_view"
  | "permission_orders_pools_details"
  | "permission_orders_pools_edit"
>;

export const ProfilePermissions: React.FC<ProfilePermissionsProps> = ({
  username,
  permission_orders_pools_view,
  permission_orders_pools_details,
  permission_orders_pools_edit,
}) => {
  const [loading, setLoading] = React.useState(false);
  const [detailsDisabled, setDetailsDisabled] = React.useState(
    !permission_orders_pools_view,
  );
  const [editDisabled, setEditDisabled] = React.useState(
    !permission_orders_pools_details,
  );
  const form = useForm<ProfilePermissionsForm>({
    mode: "uncontrolled",
    initialValues: {
      permission_orders_pools_view,
      permission_orders_pools_details,
      permission_orders_pools_edit,
    },
  });

  form.watch("permission_orders_pools_view", ({ value }) => {
    if (!value) {
      form.setFieldValue("permission_orders_pools_details", false);
      setDetailsDisabled(true);
    } else {
      setDetailsDisabled(false);
    }
  });

  form.watch("permission_orders_pools_details", ({ value }) => {
    if (!value) {
      form.setFieldValue("permission_orders_pools_edit", false);
      setEditDisabled(true);
    } else {
      setEditDisabled(false);
    }
  });

  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: "Permissions have been saved",
              color: "green",
            });
          } else {
            notifications.show({
              title: "Error",
              message: "There was a problem saving permissions",
              color: "red",
            });
          }
        })
        .finally(() => {
          setLoading(false);
        });
    }),
    [],
  );

  return (
    <Paper>
      <form onSubmit={handleSubmit}>
        <Title order={4} mb="md">
          Permissions
        </Title>
        <Checkbox
          {...form.getInputProps("permission_orders_pools_view", {
            type: "checkbox",
          })}
          key={form.key("permission_orders_pools_view")}
          label="Sub can view orders sets"
          mb="md"
        />
        <Checkbox
          {...form.getInputProps("permission_orders_pools_details", {
            type: "checkbox",
          })}
          key={form.key("permission_orders_pools_details")}
          disabled={detailsDisabled}
          label="Sub can view orders sets details"
          mb="md"
        />
        <Checkbox
          {...form.getInputProps("permission_orders_pools_edit", {
            type: "checkbox",
          })}
          key={form.key("permission_orders_pools_edit")}
          disabled={editDisabled}
          label="Sub can edit orders sets"
          mb="md"
        />
        <Button type="submit" loading={loading} mt="md">
          Save
        </Button>
      </form>
    </Paper>
  );
};
