"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { FormField } from "@/components/ui/form-field";
import { Input } from "@/components/ui/input";
import { useT } from "@/i18n";
import { friendlyErrorMessage } from "@/lib/errors";

/**
 * Asks for the password again before a credential is shown or replaced.
 *
 * A signed-in session is not enough for these: a token left on an unlocked laptop would otherwise
 * be one click from the keys that create orders. The server checks the password itself — this only
 * collects it — and says "wrong password" in its own words, which are shown under the field.
 *
 * The password lives in this component's state and is cleared the moment the dialog closes.
 */
export function PasswordConfirmDialog({
  open,
  onOpenChange,
  title,
  description,
  actionLabel,
  onConfirm,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  title: string;
  description: string;
  actionLabel: string;
  /** Should throw on failure; the message is shown under the field. */
  onConfirm: (password: string) => Promise<void>;
}) {
  const t = useT();
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [pending, setPending] = useState(false);

  function close(next: boolean) {
    if (!next) {
      setPassword("");
      setError(null);
    }
    onOpenChange(next);
  }

  async function submit(event: React.FormEvent) {
    event.preventDefault();
    if (password === "") return;

    setPending(true);
    setError(null);
    try {
      await onConfirm(password);
      close(false);
    } catch (failure) {
      setError(friendlyErrorMessage(failure, t));
    } finally {
      setPending(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={close}>
      <DialogContent>
        <form onSubmit={(event) => void submit(event)} className="space-y-4">
          <DialogHeader>
            <DialogTitle>{title}</DialogTitle>
            <DialogDescription>{description}</DialogDescription>
          </DialogHeader>
          <FormField label={t("portal.integration.confirmPassword")} htmlFor="confirm-password" error={error}>
            <Input
              id="confirm-password"
              type="password"
              autoComplete="current-password"
              autoFocus
              value={password}
              onChange={(event) => setPassword(event.target.value)}
            />
          </FormField>
          <DialogFooter>
            <Button type="button" variant="ghost" onClick={() => close(false)}>
              {t("common.cancel")}
            </Button>
            <Button type="submit" loading={pending} disabled={password === ""}>
              {actionLabel}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
