"use client";

import * as React from "react";
import { useActionState } from "react";
import { TriangleAlert } from "lucide-react";
import { Button, type ButtonProps } from "@/components/ui/button";
import { Alert } from "@/components/ui/alert";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { IDLE_ACTION, type ActionState } from "@/lib/action-state";

/**
 * Submit a server action from a button, optionally behind a confirm dialog.
 *
 * Server actions can be passed from Server to Client Components as props, so
 * this one component covers every "delete"/"publish"/"mark" affordance in the
 * app instead of each page hand-rolling its own form.
 */
export function ActionButton({
  action,
  fields = {},
  label,
  confirm,
  confirmTitle,
  confirmLabel,
  icon,
  variant = "secondary",
  size = "md",
  className,
  onDone,
}: {
  action: (state: ActionState, formData: FormData) => Promise<ActionState>;
  /** Hidden inputs submitted with the action. */
  fields?: Record<string, string | number>;
  label: React.ReactNode;
  /** When set, ask the user to confirm before submitting. */
  confirm?: string;
  confirmTitle?: string;
  confirmLabel?: string;
  icon?: React.ReactNode;
  variant?: ButtonProps["variant"];
  size?: ButtonProps["size"];
  className?: string;
  /** Called after the action settles successfully. */
  onDone?: () => void;
}) {
  const [state, formAction, pending] = useActionState(action, IDLE_ACTION);
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    if (state.status === "success") {
      setOpen(false);
      onDone?.();
    }
  }, [state.status, onDone]);

  const hiddenFields = Object.entries(fields).map(([name, value]) => (
    <input key={name} type="hidden" name={name} value={String(value)} />
  ));

  if (!confirm) {
    return (
      <form action={formAction} className={className ? undefined : "inline-flex"}>
        {hiddenFields}
        <Button type="submit" variant={variant} size={size} loading={pending} className={className}>
          {icon}
          {label}
        </Button>
      </form>
    );
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <Button
        type="button"
        variant={variant}
        size={size}
        className={className}
        onClick={() => setOpen(true)}
      >
        {icon}
        {label}
      </Button>

      <DialogContent size="sm">
        <form action={formAction}>
          {hiddenFields}
          <DialogHeader>
            <DialogTitle>{confirmTitle ?? "Konfirmasi"}</DialogTitle>
            <DialogDescription>{confirm}</DialogDescription>
          </DialogHeader>

          {state.status === "error" && state.message ? (
            <DialogBody>
              <Alert tone="danger" icon={<TriangleAlert className="size-4" />}>
                {state.message}
              </Alert>
            </DialogBody>
          ) : null}

          <DialogFooter>
            <Button type="button" variant="secondary" onClick={() => setOpen(false)}>
              Batal
            </Button>
            <Button type="submit" variant={variant === "secondary" ? "danger" : variant} loading={pending}>
              {confirmLabel ?? "Ya, lanjutkan"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
