"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;
};

const kumoBackdropClassNames =
  "fixed inset-0 bg-kumo-recessed opacity-80 transition-all duration-150 data-ending-style:opacity-0 data-starting-style:opacity-0";

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(
          "teatea-dialog dialog-panel-enter fixed left-1/2 top-1/2 z-50 flex max-h-[min(92svh,52rem)] w-[min(calc(100vw-1.5rem),48rem)] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-lg border border-kumo-line bg-kumo-base p-0 shadow-xl outline-none ring-1 ring-kumo-line",
          "data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0",
          className,
        )}
        data-kumo-backdrop-classes={kumoBackdropClassNames}
        size="xl"
      >
        <header className="flex shrink-0 items-start justify-between gap-4 border-b border-kumo-line bg-kumo-base p-5">
          <div className="min-w-0">
            <KumoDialog.Title className="text-lg font-semibold leading-7 text-kumo-strong">{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>
  );
}
