"use client";
import type { ReactNode, FormEvent } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
export function Editor({
  title,
  open,
  onClose,
  onSubmit,
  error,
  children,
  description = "Changes are local to this page and reset when you reload.",
  submitLabel = "Save preview",
  submitting = false,
  submitDisabled = false,
}: {
  title: string;
  open: boolean;
  onClose: () => void;
  onSubmit: () => void;
  error?: string;
  children: ReactNode;
  description?: string;
  submitLabel?: string;
  submitting?: boolean;
  submitDisabled?: boolean;
}) {
  function submit(e: FormEvent) {
    e.preventDefault();
    onSubmit();
  }
  return (
    <Dialog
      open={open}
      onOpenChange={(value) => {
        if (!value) onClose();
      }}
    >
      <DialogContent className="max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription>{description}</DialogDescription>
        </DialogHeader>
        <form onSubmit={submit} className="space-y-5">
          {children}
          {error && (
            <p role="alert" className="text-sm text-destructive">
              {error}
            </p>
          )}
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              disabled={submitting}
              onClick={onClose}
            >
              Cancel
            </Button>
            <Button disabled={submitting || submitDisabled}>
              {submitting ? "Saving…" : submitLabel}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
export function DeleteDialog({
  name,
  error,
  title = "Delete preview record",
  description,
  confirmation,
  submitLabel = "Delete locally",
  submitting = false,
  onClose,
  onConfirm,
}: {
  name: string;
  error?: string;
  title?: string;
  description?: string;
  confirmation?: ReactNode;
  submitLabel?: string;
  submitting?: boolean;
  onClose: () => void;
  onConfirm: () => void;
}) {
  return (
    <Editor
      title={title}
      open
      onClose={onClose}
      onSubmit={onConfirm}
      error={error}
      description={description}
      submitLabel={submitLabel}
      submitting={submitting}
    >
      {confirmation ?? (
        <p>
          Delete <strong>{name}</strong> from this local preview?
        </p>
      )}
    </Editor>
  );
}
