import React, { useRef } from "react";
import * as Dialog from "@radix-ui/react-dialog";
import { IoCloseOutline } from "react-icons/io5";
import { useForm, SubmitHandler } from "react-hook-form";
import { useToken } from "@/hooks/useToken";
import styles from "./NewActionDialog.module.css";
import CodeInput from "./CodeInput";
import { useUniqueId } from "../lib/utils";

function NewActionDialog({
  open,
  setOpen,
}: {
  open: boolean;
  setOpen: React.Dispatch<React.SetStateAction<boolean>>;
}) {
  type Inputs = {
    name: string;
    logo_url: string;
    description: string;
    categories: string;
    tags: string;
    action_type: string;
    execution_type: string;
    function_name: string;
    function_arn: string;
    assume_role_arn: string;
    form: string;
    type: string;
  };
  const formRef = useRef(null);
  const submit = () => {
    if (formRef.current) {
      // formRef.current.dispatchEvent(
      //   new Event("submit", { cancelable: true, bubbles: true })
      // );
    }
  };

  const [save, setSave] = React.useState(false);

  const { token } = useToken();
  const {
    setValue,
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<Inputs>();
  const onSubmit: SubmitHandler<Inputs> = async (data) => {
    console.log("1111>>", data);
    setSave(true);
    const r = await fetch("https://api.edgebrix.com/v1/actions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify(data),
    })
      .then((r) => {
        if (r.ok) {
          setOpen(false);
        }
      })
      .catch((e) => {
        console.log("error", e);
      })
      .finally(() => {
        setSave(false);
      });
  };

  return (
    <Dialog.Root open={open} onOpenChange={setOpen}>
      <Dialog.Portal>
        <Dialog.Overlay className={styles.DialogOverlay} />
        <Dialog.Content className={styles.DialogContent}>
          <Dialog.Title className={styles.DialogTitle}>
            Add new action
          </Dialog.Title>
          <Dialog.Description className={styles.DialogDescription}>
            Add a new action to your workflow and start automating your tasks.
          </Dialog.Description>
          <form ref={formRef} onSubmit={handleSubmit(onSubmit)}>
            <fieldset className={styles.Fieldset}>
              <label className={styles.Label} htmlFor="type">
                Action type
              </label>

              <select
                className={styles.Input}
                id="type"
                {...register("type", { required: true })}
              >
                <option value="action">Action</option>
                <option value="triger">Trigger</option>
              </select>
            </fieldset>

            <fieldset className={styles.Fieldset}>
              <label className={styles.Label} htmlFor="name">
                Name
              </label>
              <input
                className={styles.Input}
                id="name"
                defaultValue=""
                {...register("name", { required: true })}
              />
            </fieldset>
            <fieldset className={styles.Fieldset}>
              <label className={styles.Label} htmlFor="description">
                Description
              </label>
              <input
                className={styles.Input}
                id="description"
                defaultValue=""
                {...register("description")}
              />
            </fieldset>

            <fieldset className={styles.Fieldset}>
              <label className={styles.Label} htmlFor="logo_url">
                Action image URL
              </label>
              <input
                className={styles.Input}
                id="logo_url"
                defaultValue="https://res.cloudinary.com/dhwxfvlrn/image/upload/f_auto,q_auto,dpr_2/icons/lambda_action.png"
                {...register("logo_url")}
              />
            </fieldset>

            <fieldset className={styles.Fieldset}>
              <label className={styles.Label} htmlFor="FunctionName">
                Function name
              </label>
              <input
                className={styles.Input}
                id="function_name"
                defaultValue=""
                {...register("function_name", { required: true })}
              />
            </fieldset>

            <fieldset className={styles.Fieldset}>
              <label className={styles.Label} htmlFor="function_arn">
                Function ARN
              </label>
              <input
                className={styles.Input}
                id="function_arn"
                defaultValue=""
                {...register("function_arn", { required: true })}
              />
            </fieldset>

            <fieldset className={styles.Fieldset}>
              <label className={styles.Label} htmlFor="assume_role_arn">
                Assume role ARN
              </label>
              <input
                className={styles.Input}
                id="assume_role_arn"
                defaultValue=""
                {...register("assume_role_arn", { required: true })}
              />
            </fieldset>

            <fieldset className={styles.Fieldset}>
              <label className={styles.Label} htmlFor="execution_type">
                Exection type
              </label>

              <select
                className={styles.Input}
                id="execution_type"
                {...register("execution_type", { required: true })}
              >
                <option value="sync">Sync</option>
                <option value="async">Async</option>
              </select>
            </fieldset>

            <fieldset className={styles.Fieldset}>
              <label className={styles.Label} htmlFor="form">
                Form UI
              </label>

              <CodeInput
                setValue={setValue}
                register={register}
                code={"[]"}
                name={"form"}
                mode={"javascript"}
              />
            </fieldset>

            {Object.keys(errors).length > 0 && (
              <span>Please make sure to fill all values</span>
            )}

            {/* <input type="submit" /> */}
          </form>

          <div
            style={{
              display: "flex",
              marginTop: 25,
              justifyContent: "flex-end",
            }}
          >
            <button
              onClick={() => {
                console.log(errors);
                submit();
                //setOpen(false)
              }}
              className={styles.ButtonGreen}
            >
              {!save ? <>Create action</> : <>Please wait...</>}
            </button>
          </div>

          <div onClick={() => setOpen(false)}>
            <button className={styles.IconButton} aria-label="Close">
              <IoCloseOutline />
            </button>
          </div>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
}

export { NewActionDialog };
