import { createAlias } from "@/lib/actions";
import { AliasEntry } from "@/lib/db";
import { ToastContext } from "@/lib/providers/ToastProvider";
import { Button, Callout, Dialog, Flex, TextField } from "@radix-ui/themes";
import { AtSignIcon, MailWarningIcon } from "lucide-react";
import { useContext, useState } from "react";

export default function CreateAliasButton({ user, onCreate }: { user: string, onCreate?: (alias: AliasEntry) => any }) {
  const [value, setValue] = useState("");
  const toast = useContext(ToastContext);

  return (
    <Dialog.Root onOpenChange={(open) => !open && setValue("")}>
      <Dialog.Trigger>
        <Button variant="outline" size="1">Add alias</Button>
      </Dialog.Trigger>
      <Dialog.Content>
        <Dialog.Title>Create alias</Dialog.Title>

        <Callout.Root mb="4">
          <Callout.Icon>
            <MailWarningIcon />
          </Callout.Icon>
          <Callout.Text>Make sure the alias uses a valid domain!</Callout.Text>
        </Callout.Root>

        <TextField.Root>
          <TextField.Slot>
            <AtSignIcon size="16" />
          </TextField.Slot>
          <TextField.Input
            placeholder={`${user.split("@")[0]}@alias.domain`}
            value={value}
            onChange={(e) => setValue(e.currentTarget.value.toLowerCase())}
          />
        </TextField.Root>

        <Flex gap="3" mt="4" justify="end">
          <Dialog.Close>
            <Button variant="surface">Cancel</Button>
          </Dialog.Close>
          <Dialog.Close>
            <Button
              variant="surface"
              disabled={!value.includes("@")}
              onClick={async () => {
                try {
                  const alias = await createAlias(user, value);
                  onCreate?.(alias);
                  toast({
                    title: "Alias created",
                    description: value,
                    variant: "success",
                  });
                } catch (e) {
                  console.error(e);
                  toast({
                    title: "Failed to create alias",
                    description: `${e}`,
                    variant: "error",
                  });
                }
              }}
            >Create</Button>
          </Dialog.Close>
        </Flex>
      </Dialog.Content>
    </Dialog.Root>
  );
}