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

type UndoEntry = {
  id: number;
  text: string;
  onUndo: () => void | Promise<void>;
};

type Listener = (entry: UndoEntry | null) => void;

const TOAST_DURATION_MS = 5000;

let nextId = 1;
const listeners = new Set<Listener>();
let timer: ReturnType<typeof setTimeout> | null = null;

function broadcast(entry: UndoEntry | null): void {
  for (const l of listeners) l(entry);
}

function clearTimerIfAny(): void {
  if (timer !== null) {
    clearTimeout(timer);
    timer = null;
  }
}

export function pushTagUndo(opts: {
  noteId: string;
  tag: { name: string };
  onUndo: () => void | Promise<void>;
}): void {
  const entry: UndoEntry = {
    id: nextId++,
    text: `'#${opts.tag.name}' 제거됨 · 되돌리기`,
    onUndo: opts.onUndo
  };
  clearTimerIfAny();
  broadcast(entry);
  timer = setTimeout(() => {
    timer = null;
    broadcast(null);
  }, TOAST_DURATION_MS);
}

export function TagUndoToast(): React.ReactElement | null {
  const [entry, setEntry] = useState<UndoEntry | null>(null);

  useEffect(() => {
    const l: Listener = (e) => setEntry(e);
    listeners.add(l);
    return () => { listeners.delete(l); };
  }, []);

  if (entry === null) return null;

  return (
    <div
      onClick={async () => {
        clearTimerIfAny();
        const e = entry;
        setEntry(null);
        broadcast(null);
        try { await e.onUndo(); } catch { /* swallow — best-effort restore */ }
      }}
      style={{
        position: 'fixed',
        bottom: 16,
        left: '50%',
        transform: 'translateX(-50%)',
        background: '#333',
        color: 'white',
        padding: '8px 14px',
        borderRadius: 6,
        fontSize: 13,
        cursor: 'pointer',
        boxShadow: '0 2px 6px rgba(0,0,0,0.2)',
        zIndex: 1000
      }}
      role="alert"
    >
      {entry.text}
    </div>
  );
}
