import React, { useEffect, 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 "../ActionDialog.module.css";
import { useCurrentFlow } from "@/hooks/useCurrentFlow";
import { api_endpoint } from "@/components/lib/utils";

function WebhookDialog({
  open,
  setOpen,
}: {
  open: boolean;
  setOpen: React.Dispatch<React.SetStateAction<boolean>>;
}) {
  const [loading, setLoading] = React.useState(false);
  const [url, setUrl] = React.useState("");
  const { token } = useToken();

  const { currentFlowId } = useCurrentFlow();

  useEffect(() => {
    console.log("currentFlowId", currentFlowId);
    if (!currentFlowId) return;
    (async () => {
      setLoading(true);
      const r = await fetch(`${api_endpoint}/hooks/${currentFlowId}`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
      });

      const data = await r.json();
      setUrl(`https://hooks.edgebrix.com/${data.webhook_id}`);
      setLoading(false);
    })();
  }, [currentFlowId]);

  return (
    <Dialog.Root open={open} onOpenChange={setOpen}>
      <Dialog.Portal>
        <Dialog.Overlay className={styles.DialogOverlay} />
        <Dialog.Content className={styles.DialogContent}>
          <Dialog.Title className={styles.DialogTitle}>Webhook</Dialog.Title>
          <Dialog.Description
            className={styles.DialogDescription}
          ></Dialog.Description>
          <fieldset className="Fieldset">
            <label className="Label" htmlFor="url">
              {loading ? "Loading..." : url}
            </label>
          </fieldset>
          <div
            style={{
              display: "flex",
              marginTop: 25,
              justifyContent: "flex-end",
            }}
          >
            <div
              style={{
                display: "flex",
                marginTop: 25,
                justifyContent: "flex-end",
              }}
            >
              <Dialog.Close asChild>
                <button className={styles.ButtonGreen}>Close</button>
              </Dialog.Close>
            </div>
          </div>

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

export { WebhookDialog };
