"use client";

import { useRef, type ReactNode } from "react";

export type ActionMenuItem = {
  label: string;
  description?: string;
  icon?: ReactNode;
  disabled?: boolean;
  danger?: boolean;
  onClick: () => void;
};

export default function ActionMenu({
  label = "Lainnya",
  items,
  align = "right",
  compact = false,
}: {
  label?: string;
  items: ActionMenuItem[];
  align?: "left" | "right";
  compact?: boolean;
}) {
  const ref = useRef<HTMLDetailsElement>(null);

  return (
    <details className="relative" ref={ref}>
      <summary
        className={[
          "flex cursor-pointer list-none items-center justify-center gap-2 rounded-[10px] border border-slate-200 bg-white font-bold text-slate-700 shadow-sm transition hover:border-slate-300 hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800 [&::-webkit-details-marker]:hidden",
          compact ? "h-8 min-w-8 px-2 text-[11px]" : "min-h-9 px-3 py-2 text-[13px]",
        ].join(" ")}
      >
        <span>{label}</span>
        <svg aria-hidden="true" className="h-3.5 w-3.5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path d="m7 10 5 5 5-5" /></svg>
      </summary>
      <div className={[
        "absolute z-50 mt-2 w-60 overflow-hidden rounded-xl border border-slate-200 bg-white p-1.5 shadow-xl shadow-slate-950/10 dark:border-slate-700 dark:bg-slate-900",
        align === "right" ? "right-0" : "left-0",
      ].join(" ")}>
        {items.map((item) => (
          <button
            className={[
              "flex w-full items-start gap-2.5 rounded-lg px-3 py-2.5 text-left transition",
              item.danger ? "text-rose-700 hover:bg-rose-50 dark:text-rose-300 dark:hover:bg-rose-950/40" : "text-slate-700 hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800",
              item.disabled ? "cursor-not-allowed opacity-40" : "",
            ].join(" ")}
            disabled={item.disabled}
            key={item.label}
            onClick={() => {
              ref.current?.removeAttribute("open");
              item.onClick();
            }}
            type="button"
          >
            {item.icon ? <span className="mt-0.5 text-slate-400">{item.icon}</span> : null}
            <span><span className="block text-[12px] font-bold">{item.label}</span>{item.description ? <span className="mt-0.5 block text-[10px] leading-4 text-slate-400">{item.description}</span> : null}</span>
          </button>
        ))}
      </div>
    </details>
  );
}
