import { Button, Callout, Dialog, Flex, IconButton, TextArea, TextField } from "@radix-ui/themes";
import crypto from "crypto";
import { AsteriskIcon, AtSignIcon, EyeIcon, EyeOffIcon, UserIcon } from "lucide-react";
import { useState } from "react";
import GhostMessage from "../GhostMessage";
import LoadingSpinner from "../LoadingSpinner";
import { createUser } from "@/lib/actions";

export default function CreateUserButton({ onCreate }: { onCreate?: (email: string) => any }) {
  const [passwordHidden, setPasswordHidden] = useState(true);
  const [password, setPassword] = useState("");
  const [email, setEmail] = useState("");
  const [open, setOpen] = useState(false);
  const [state, setState] = useState<"input" | "loading" | "created">("input");
  const textAreaString = `Email: ${email}\nPassword: ${password}\nLogin: https://mail.amogus.cloud`;

  return (
    <Dialog.Root open={open} onOpenChange={(open) => {
      setOpen(open);
      if (!open) {
        setState("input");
        setPasswordHidden(true);
        setPassword("");
        setEmail("");
      }
    }}>
      <Dialog.Trigger>
        <Button variant="outline">Create user</Button>
      </Dialog.Trigger>

      <Dialog.Content>
        <Dialog.Title>Create user</Dialog.Title>
        {
          state == "input"
            ? <>
              <Dialog.Description>Provide the user&apos;s primary email address and a password. The user can change their password later.</Dialog.Description>

              <Callout.Root my="4">
                <Callout.Icon>
                  <AtSignIcon />
                </Callout.Icon>
                <Callout.Text>
                  Make sure that the provided email address uses a configured domain!
                </Callout.Text>
              </Callout.Root>

              <Flex direction="column" gap="3">
                <TextField.Root>
                  <TextField.Slot>
                    <UserIcon />
                  </TextField.Slot>
                  <TextField.Input
                    placeholder="username@amogus.cloud"
                    type="text"
                    value={email}
                    onChange={(e) => setEmail(e.currentTarget.value)}
                  />
                </TextField.Root>
                <Flex gap="3">
                  <TextField.Root className="grow">
                    <TextField.Slot>
                      <AsteriskIcon />
                    </TextField.Slot>
                    <TextField.Input
                      placeholder={passwordHidden ? "\u25CF".repeat(10) : "sussyballs"}
                      type={passwordHidden ? "password" : "text"}
                      value={password}
                      onChange={(e) => setPassword(e.currentTarget.value)}
                    />
                    <TextField.Slot>
                      <IconButton onClick={() => setPasswordHidden(!passwordHidden)} size="1" variant="ghost">
                        {
                          passwordHidden
                            ? <EyeOffIcon size="16" />
                            : <EyeIcon size="16" />
                        }
                      </IconButton>
                    </TextField.Slot>
                  </TextField.Root>
                  <Button variant="outline"
                    onClick={() => setPassword(crypto.randomBytes(24).toString("base64"))}
                  >
                    Generate
                  </Button>
                </Flex>
              </Flex>

              <Flex gap="3" mt="4" justify="end">
                <Dialog.Close>
                  <Button variant="outline">Cancel</Button>
                </Dialog.Close>
                <Button
                  variant="soft"
                  disabled={password.length < 8 || !email.length || !email.includes("@")}
                  onClick={async () => {
                    setState("loading");
                    await createUser(email, password);
                    setState("created");
                    onCreate?.(email);
                  }}
                >
                  Create
                </Button>
              </Flex>
            </>
            : state == "loading"
              ? <GhostMessage icon={<LoadingSpinner />} header="Creating user..." />
              : <>
                <Dialog.Description>
                  Provide the user with the following text block to allow them to log in:
                </Dialog.Description>
                <Flex direction="column">
                  <TextArea
                    variant="surface"
                    value={textAreaString}
                    className="h-[4.5rem] mt-4 w-full"
                    disabled
                  />
                </Flex>

                <Flex gap="3" mt="4" justify="end">
                  <Dialog.Close>
                    <Button variant="surface" onClick={() => navigator.clipboard.writeText(textAreaString)}>Copy and close</Button>
                  </Dialog.Close>
                  <Dialog.Close>
                    <Button variant="surface">Close</Button>
                  </Dialog.Close>
                </Flex>
              </>
        }
      </Dialog.Content>
    </Dialog.Root>
  );
}