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

const dialogWidthValues = {
  sm: "28rem",
  md: "36rem",
  lg: "42rem",
  xl: "48rem",
  wide: "64rem",
} as const;

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

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

type DialogStyle = React.CSSProperties & {
  "--dialog-width": string;
};

export function Dialog({
  open,
  title,
  description,
  children,
  footer,
  onClose,
  className,
  width = "md",
}: DialogProps): React.ReactElement {
  const dialogStyle: DialogStyle = {
    "--dialog-width": dialogWidthValues[width],
    transform: "none",
    translate: "0 0",
  };

  return (
    <KumoDialog.Root
      onOpenChange={(nextOpen) => {
        if (!nextOpen) {
          onClose();
        }
      }}
      open={open}
    >
      <KumoDialog
        className={cn(
          "teatea-dialog fixed inset-0 z-50 m-auto flex h-fit max-h-[min(calc(100svh-1.5rem),52rem)] w-[min(calc(100vw-1.5rem),var(--dialog-width))] min-w-0 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"
        style={dialogStyle}
      >
        <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>
  );
}
