"use client";
import React from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "../ui/dialog";
import useConfirmDialogStore from "@/store/useConfirmDialogStore";
import { Button } from "../ui/button";
import { Root, createRoot } from "react-dom/client";
import { DialogClose } from "@radix-ui/react-dialog";

type ConfirmDialogT = {
  onOkay: () => void;
  onCancel: () => void;
  onClose: () => void;
  open: boolean;
  title: string;
  description: string;
};

const ConfirmDialog = ({
  onCancel,
  onOkay,
  open,
  description,
  onClose,
  title,
}: ConfirmDialogT) => {
  return (
    <div>
      <Dialog open={open} onOpenChange={onClose}>
        {/* <DialogTrigger>Open</DialogTrigger> */}

        <DialogContent className="w-fit px-10">
          <DialogHeader>
            <DialogTitle>{title}</DialogTitle>
            <DialogDescription className="mx-auto">
              {description}
              <div className="flex gap-3 mt-5">
                <Button className="w-20" onClick={() => onOkay()}>
                  Yes
                </Button>

                <Button
                  className="w-20"
                  variant="destructive"
                  onClick={() => onCancel()}
                >
                  Cancel
                </Button>
              </div>
            </DialogDescription>
          </DialogHeader>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export function confirmModla(title: string = "", description: string = "") {
  const checkIfThere = document.querySelector("#confirm-modal");
  let container: Element;
  let root: Root;

  if (!checkIfThere) {
    container = document.createElement("div");
    container.setAttribute("id", "confirm-modal");
    document.querySelector("body")?.appendChild(container);
    root = createRoot(container);
  } else {
    root = createRoot(checkIfThere);
  }

  const { toggle } = useConfirmDialogStore.getState();
  return new Promise((resolve, reject) => {
    toggle();

    function onClose() {
      reject(false);
      root.unmount();
    }

    function onClickOk() {
      resolve(true);
      onClose();
    }

    function onClickCancel() {
      reject(false);
      onClose();
    }

    root.render(
      <ConfirmDialog
        onOkay={onClickOk}
        onCancel={onClickCancel}
        onClose={onClose}
        open={true}
        title={title}
        description={description}
      />
    );
  });
}

export default ConfirmDialog;
