"use client";

import { useEffect, useRef, useState } from "react";
import { Icon } from "@/components/ui/Icon";

// ──────────────────────────────────────────────────────────────────────────
// Zentrale PIN-Eingabe: abgedunkelter Hintergrund, sofort tippbereit,
// bestätigt automatisch bei vollständiger Eingabe. Bei falscher PIN wird die
// Maske über einen neuen `key` frisch aufgebaut — leer, rot und wackelnd.
// ──────────────────────────────────────────────────────────────────────────

export function PinDialog({
  title,
  length,
  hint,
  busy,
  error,
  onSubmit,
  onClose,
}: {
  title: string;
  length: number;
  hint: string | null;
  busy: boolean;
  error: string | null;
  onSubmit: (pin: string) => void;
  onClose: () => void;
}) {
  const [pin, setPin] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);
  const submittedRef = useRef("");

  // Fokus setzen und mit Escape schließen.
  useEffect(() => {
    inputRef.current?.focus();
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const change = (raw: string) => {
    if (busy) return;
    const digits = raw.replace(/\D/g, "").slice(0, length);
    setPin(digits);
    if (digits.length === length && submittedRef.current !== digits) {
      submittedRef.current = digits;
      onSubmit(digits);
    }
  };

  // Solange getippt wird, ist die Fehlermeldung von der vorigen Eingabe.
  const showError = Boolean(error) && pin.length === 0;

  return (
    <div className="pin-overlay" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <div className="pin-modal" role="dialog" aria-modal="true" data-error={showError}>
        <div className="pin-shake" data-error={showError}>
        <span
          className="mx-auto grid h-12 w-12 place-items-center rounded-2xl"
          style={{
            background: showError ? "rgba(255,122,156,.18)" : "rgba(255,159,215,.14)",
            color: "var(--pink)",
            border: "1px solid var(--line)",
          }}
        >
          <Icon name="lock" size={22} />
        </span>

        <h3 className="mt-3">PIN eingeben</h3>
        <p className="text-muted mt-1 truncate text-sm">
          <span className="font-bold">{title}</span>
        </p>

        <div className="pin-boxes" onClick={() => inputRef.current?.focus()}>
          {Array.from({ length }, (_, i) => (
            <span
              key={i}
              className="pin-box"
              data-filled={i < pin.length}
              data-active={i === pin.length && !busy && !showError}
            >
              {i < pin.length ? "•" : ""}
            </span>
          ))}
          <input
            ref={inputRef}
            className="pin-input"
            type="text"
            inputMode="numeric"
            autoComplete="one-time-code"
            value={pin}
            maxLength={length}
            disabled={busy}
            onChange={(e) => change(e.target.value)}
            aria-label={`PIN, ${length} Ziffern`}
          />
        </div>

        {/* Feste Höhe, damit der Dialog beim Fehler nicht springt. */}
        <div className="mt-2 flex min-h-[34px] items-center justify-center">
          {busy ? (
            <span className="text-muted text-xs font-bold">Wird geprüft …</span>
          ) : showError ? (
            <span
              className="inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-black"
              style={{
                color: "var(--pink)",
                background: "rgba(255,122,156,.12)",
                border: "1px solid rgba(255,122,156,.32)",
              }}
            >
              <Icon name="alert" size={13} /> {error}
            </span>
          ) : hint ? (
            <span className="text-muted text-xs">Hinweis: {hint}</span>
          ) : (
            <span className="text-muted text-xs">{length} Ziffern · bestätigt automatisch</span>
          )}
        </div>

        <button className="btn btn-ghost btn-sm mt-3" onClick={onClose} disabled={busy}>
          Abbrechen
        </button>
        </div>
      </div>
    </div>
  );
}
