"use client";

import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "~/app/_components/ui/dialog";
import { Button } from "~/app/_components/ui/button";
import { createContext, useContext, useState } from "react";

type DialogContextType = (options: {
  title?: string;
  description?: string;
  confirmText?: string;
  cancelText?: string;
}) => Promise<boolean>;

const DialogContext = createContext<DialogContextType | null>(null);

export const useDialogConfirmation = () => {
  const context = useContext(DialogContext);
  if (!context) {
    throw new Error("useDialogConfirmation must be used within DialogProvider");
  }
  return context;
};

export const DialogProvider = ({ children }: { children: React.ReactNode }) => {
  const [dialogState, setDialogState] = useState<{
    isOpen: boolean;
    options: {
      title?: string;
      description?: string;
      confirmText?: string;
      cancelText?: string;
    };
    resolve: ((value: boolean) => void) | null;
  }>({
    isOpen: false,
    options: {},
    resolve: null,
  });

  const dialogConfirmation: DialogContextType = (options) =>
    new Promise((resolve) => {
      setDialogState({
        isOpen: true,
        options,
        resolve,
      });
    });

  const handleConfirm = () => {
    if (dialogState.resolve) dialogState.resolve(true);
    setDialogState({ ...dialogState, isOpen: false });
  };

  const handleCancel = () => {
    if (dialogState.resolve) dialogState.resolve(false);
    setDialogState({ ...dialogState, isOpen: false });
  };

  return (
    <DialogContext.Provider value={dialogConfirmation}>
      {children}
      <Dialog
        open={dialogState.isOpen}
        onOpenChange={(isOpen) => setDialogState({ ...dialogState, isOpen })}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              {dialogState.options.title ?? "Are you sure?"}
            </DialogTitle>
          </DialogHeader>
          <p>
            {dialogState.options.description ?? "This action cannot be undone."}
          </p>
          <DialogFooter>
            <Button variant="secondary" onClick={handleCancel}>
              {dialogState.options.cancelText ?? "Cancel"}
            </Button>
            <Button variant="destructive" onClick={handleConfirm}>
              {dialogState.options.confirmText ?? "Confirm"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </DialogContext.Provider>
  );
};
