"use client";

import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { useT } from "@/i18n";

export function ConfirmDialog({
  open,
  onOpenChange,
  title,
  description,
  confirmLabel,
  cancelLabel,
  destructive = false,
  loading = false,
  onConfirm,
  extraAction,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  title: string;
  description?: string;
  confirmLabel?: string;
  cancelLabel?: string;
  destructive?: boolean;
  loading?: boolean;
  onConfirm: () => void | Promise<void>;
  /**
   * A second decision the same confirmation offers — not a variation of the first.
   *
   * For the case where a step has two honest answers, such as offering an order to a captain or
   * directing an employee to carry it. Left out, the dialog is exactly as it was.
   */
  extraAction?: {
    label: string;
    /** One line under the buttons saying how this differs from confirming. */
    hint?: string;
    onAct: () => void | Promise<void>;
  };
}) {
  const t = useT();
  const [localLoading, setLocalLoading] = useState(false);

  const busy = loading || localLoading;

  async function handleConfirm() {
    setLocalLoading(true);
    try {
      await onConfirm();
    } finally {
      setLocalLoading(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          {description ? <DialogDescription>{description}</DialogDescription> : null}
        </DialogHeader>
        {extraAction?.hint ? (
          <p className="text-xs text-muted-foreground">{extraAction.hint}</p>
        ) : null}
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={busy}>
            {cancelLabel ?? t("common.cancel")}
          </Button>
          {extraAction ? (
            <Button variant="outline" onClick={() => void extraAction.onAct()} disabled={busy}>
              {extraAction.label}
            </Button>
          ) : null}
          <Button
            variant={destructive ? "destructive" : "default"}
            onClick={handleConfirm}
            loading={busy}
          >
            {confirmLabel ?? t("common.confirm")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}