"use client";

import * as React from "react";
import { X } from "lucide-react";
import { Dialog as KumoDialog } from "@cloudflare/kumo/components/dialog";

import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

type DialogProps = {
  open: boolean;
  title: string;
  description?: string;
  children: React.ReactNode;
  footer?: React.ReactNode;
  onClose: () => void;
  className?: string;
};

export function Dialog({
  open,
  title,
  description,
  children,
  footer,
  onClose,
  className,
}: DialogProps): React.ReactElement {
  return (
    <KumoDialog.Root
      onOpenChange={(nextOpen) => {
        if (!nextOpen) {
          onClose();
        }
      }}
      open={open}
    >
      <KumoDialog
        className={cn(
          "flex max-h-[92svh] w-[min(calc(100vw-1.5rem),48rem)] flex-col overflow-hidden rounded-lg border border-kumo-line bg-kumo-base p-0 shadow-xl",
          className,
        )}
        size="xl"
      >
        <header className="flex shrink-0 items-start justify-between gap-4 border-b border-kumo-line p-5">
          <div className="min-w-0">
            <KumoDialog.Title>{title}</KumoDialog.Title>
            {description ? <KumoDialog.Description className="mt-1">{description}</KumoDialog.Description> : null}
          </div>
          <Button aria-label="关闭弹窗" onClick={onClose} size="icon" type="button" variant="outline">
            <X className="size-4" aria-hidden="true" />
          </Button>
        </header>
        <div className="min-h-0 flex-1 overflow-y-auto p-5">{children}</div>
        {footer ? <footer className="shrink-0 border-t border-kumo-line bg-kumo-recessed p-4">{footer}</footer> : null}
      </KumoDialog>
    </KumoDialog.Root>
  );
}
