"use client";

// ──────────────────────────────────────────────────────────────────────────
// Globales, im Avaria-Stil gestaltetes Dialogsystem als Ersatz für die
// nativen window.confirm / window.prompt / window.alert.
// Nutzung: `await confirmDialog({ ... })`, `await promptDialog({ ... })`,
// `await alertDialog({ ... })`. Einmalig <DialogHost/> im Layout einhängen.
// ──────────────────────────────────────────────────────────────────────────

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

type DialogKind = "confirm" | "prompt" | "alert";

type DialogRequest = {
  id: number;
  kind: DialogKind;
  title: string;
  message?: string;
  confirmLabel?: string;
  cancelLabel?: string;
  danger?: boolean;
  placeholder?: string;
  defaultValue?: string;
  multiline?: boolean;
  resolve: (value: boolean | string | null) => void;
};

let current: DialogRequest | null = null;
let counter = 0;
const listeners = new Set<() => void>();
function emit() {
  listeners.forEach((l) => l());
}

function open(req: Omit<DialogRequest, "id" | "resolve">) {
  return new Promise<boolean | string | null>((resolve) => {
    current = { ...req, id: ++counter, resolve };
    emit();
  });
}

export function confirmDialog(opts: {
  title: string;
  message?: string;
  confirmLabel?: string;
  cancelLabel?: string;
  danger?: boolean;
}): Promise<boolean> {
  return open({ kind: "confirm", ...opts }) as Promise<boolean>;
}

export function promptDialog(opts: {
  title: string;
  message?: string;
  defaultValue?: string;
  placeholder?: string;
  confirmLabel?: string;
  cancelLabel?: string;
  multiline?: boolean;
}): Promise<string | null> {
  return open({ kind: "prompt", ...opts }) as Promise<string | null>;
}

export function alertDialog(opts: {
  title: string;
  message?: string;
  confirmLabel?: string;
  danger?: boolean;
}): Promise<void> {
  return open({ kind: "alert", ...opts }).then(() => undefined);
}

export function DialogHost() {
  const [req, setReq] = useState<DialogRequest | null>(current);
  const [value, setValue] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);
  const areaRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    const sync = () => {
      setReq(current);
      if (current?.kind === "prompt") setValue(current.defaultValue ?? "");
    };
    listeners.add(sync);
    return () => {
      listeners.delete(sync);
    };
  }, []);

  useEffect(() => {
    if (req?.kind === "prompt") {
      requestAnimationFrame(() => {
        const el = req.multiline ? areaRef.current : inputRef.current;
        el?.focus();
        el?.select();
      });
    }
  }, [req]);

  if (!req) return null;

  const finish = (result: boolean | string | null) => {
    req.resolve(result);
    current = null;
    emit();
  };
  const onConfirm = () => {
    if (req.kind === "prompt") finish(value.trim() ? value : "");
    else finish(true);
  };
  const onCancel = () => finish(req.kind === "prompt" ? null : false);

  return (
    <div
      className="dialog-overlay"
      onMouseDown={(e) => e.target === e.currentTarget && onCancel()}
    >
      <div className="dialog-card animate-in" role="dialog" aria-modal="true">
        <div className="mb-2 flex items-start gap-3">
          <span className={`dialog-icon ${req.danger ? "is-danger" : ""}`}>
            <Icon name={req.danger ? "trash" : req.kind === "alert" ? "bell" : "shield"} size={18} />
          </span>
          <div className="min-w-0 flex-1">
            <h3 className="leading-tight">{req.title}</h3>
            {req.message ? <p className="text-muted mt-1 text-sm">{req.message}</p> : null}
          </div>
        </div>

        {req.kind === "prompt" ? (
          <div className="mt-3">
            {req.multiline ? (
              <textarea
                ref={areaRef}
                className="textarea"
                style={{ minHeight: 90 }}
                value={value}
                placeholder={req.placeholder}
                onChange={(e) => setValue(e.target.value)}
              />
            ) : (
              <input
                ref={inputRef}
                className="input"
                value={value}
                placeholder={req.placeholder}
                onChange={(e) => setValue(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    e.preventDefault();
                    onConfirm();
                  }
                }}
              />
            )}
          </div>
        ) : null}

        <div className="mt-5 flex items-center justify-end gap-2">
          {req.kind !== "alert" ? (
            <button className="btn btn-ghost" onClick={onCancel}>
              {req.cancelLabel ?? "Abbrechen"}
            </button>
          ) : null}
          <button
            className={`btn ${req.danger ? "btn-danger" : "btn-primary"}`}
            onClick={onConfirm}
          >
            {req.confirmLabel ?? (req.kind === "alert" ? "OK" : req.danger ? "Löschen" : "Bestätigen")}
          </button>
        </div>
      </div>
    </div>
  );
}
