import { overlay } from 'overlay-kit';

import { Button } from '@/shared/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/shared/ui/dialog';

interface ConfirmDialogOptions {
  title: string;
  description?: string;
  confirmLabel?: string;
  cancelLabel?: string;
  tone?: 'default' | 'destructive';
}

interface ConfirmDialogProps extends ConfirmDialogOptions {
  isOpen: boolean;
  onResolve: (confirmed: boolean) => void;
}

export const openConfirmDialog = (options: ConfirmDialogOptions) =>
  overlay.openAsync<boolean>(({ isOpen, close, unmount }) => (
    <ConfirmDialog
      {...options}
      isOpen={isOpen}
      onResolve={(confirmed) => {
        close(confirmed);
        unmount();
      }}
    />
  ));

const ConfirmDialog = ({
  title,
  description,
  confirmLabel = '확인',
  cancelLabel = '취소',
  tone = 'default',
  isOpen,
  onResolve,
}: ConfirmDialogProps) => {
  return (
    <Dialog
      open={isOpen}
      onOpenChange={(open) => {
        if (!open) {
          onResolve(false);
        }
      }}
    >
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          {description !== undefined && (
            <DialogDescription>{description}</DialogDescription>
          )}
        </DialogHeader>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={() => onResolve(false)}
          >
            {cancelLabel}
          </Button>
          <Button
            type="button"
            variant={tone === 'destructive' ? 'destructive' : 'default'}
            onClick={() => onResolve(true)}
          >
            {confirmLabel}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
