import { useEffect, useRef, useState } from 'react';

import { getNickname, setNickname } from '../lib/friendNicknames';

interface Props {
  open: boolean;
  userId: string;
  displayName: string;
  onClose: () => void;
}

export function NicknameDialog({ open, userId, displayName, onClose }: Props) {
  const [value, setValue] = useState('');
  const inputRef = useRef<HTMLInputElement | null>(null);

  useEffect(() => {
    if (!open) return;
    setValue(getNickname(userId) ?? '');
    setTimeout(() => inputRef.current?.focus(), 0);
  }, [open, userId]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  const submit = (): void => {
    setNickname(userId, value);
    onClose();
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="Spitzname setzen"
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
      onClick={onClose}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="w-full max-w-sm rounded-2xl border border-line bg-surface-2 p-5 shadow-xl"
      >
        <h3 className="font-display text-base font-semibold text-fg">Spitzname für {displayName}</h3>
        <p className="mt-1 text-xs text-fg-muted">
          Nur du siehst diesen Namen. Leer lassen = den richtigen Namen verwenden.
        </p>
        <input
          ref={inputRef}
          type="text"
          value={value}
          onChange={(e) => setValue(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') submit(); }}
          maxLength={32}
          placeholder={displayName}
          className="mt-4 w-full rounded-lg border border-line bg-surface-3 px-3 py-2 text-sm text-fg placeholder-fg-muted focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
        />
        <div className="mt-4 flex justify-end gap-2">
          <button
            type="button"
            onClick={onClose}
            className="cursor-pointer rounded-md border border-line bg-surface-3 px-3 py-2 text-sm text-fg hover:bg-surface-2"
          >
            Abbrechen
          </button>
          <button
            type="button"
            onClick={submit}
            className="cursor-pointer rounded-md bg-accent px-3 py-2 text-sm font-semibold text-accent-fg hover:brightness-110"
          >
            Speichern
          </button>
        </div>
      </div>
    </div>
  );
}
