// ConfirmPopup.tsx
import React, { useEffect, useMemo, useState, useCallback } from 'react';
import ReactDOM from 'react-dom';
import Button from '@mui/material/Button';
import LinearProgress from '@mui/material/LinearProgress';

declare global {
  interface Window {
    /**
     * Öffnet ein Bestätigungs-Popup als Promise.
     * Gibt true (bestätigt) oder false (abgebrochen) zurück.
     */
    confirmPopup: (options: ConfirmOptions) => Promise<boolean>;
  }
}

export type ConfirmOptions = {
  title?: string;
  message?: React.ReactNode;
  confirmLabel?: string;
  cancelLabel?: string;
  /** Setze auf true für "gefährliche" Aktionen (rote Bestätigungstaste) */
  danger?: boolean;
  /** Optionaler Ladezustand nach Klick auf Bestätigen (z. B. bei async Workflows) */
  showLoadingAfterConfirm?: boolean;
};

type QueueItem = {
  id: number;
  options: ConfirmOptions;
  resolve: (ok: boolean) => void;
};

const queue: QueueItem[] = (window as any)._confirmPopupQueue || [];
let _counter = 0;

// Vorläufige globale Funktion bis React-Komponente mounted
if (typeof window.confirmPopup !== 'function') {
  window.confirmPopup = (options: ConfirmOptions) => {
    return new Promise<boolean>((resolve) => {
      queue.push({ id: ++_counter, options, resolve });
    });
  };
  (window as any)._confirmPopupQueue = queue;
}

const ConfirmPopup: React.FC = () => {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [current, setCurrent] = useState<QueueItem | null>(null);

  // Defaults
  const opts = useMemo<Required<ConfirmOptions>>(
    () => ({
      title: current?.options.title ?? 'Bestätigen',
      message: current?.options.message ?? 'Sind Sie sicher?',
      confirmLabel: current?.options.confirmLabel ?? 'Bestätigen',
      cancelLabel: current?.options.cancelLabel ?? 'Abbrechen',
      danger: current?.options.danger ?? false,
      showLoadingAfterConfirm: current?.options.showLoadingAfterConfirm ?? false,
    }),
    [current]
  );

  // Beim Mount: globale Funktion final setzen (keine Queue verlieren)
  useEffect(() => {
    window.confirmPopup = (options: ConfirmOptions) => {
      return new Promise<boolean>((resolve) => {
        queue.push({ id: ++_counter, options, resolve });
        pump();
      });
    };
    // evtl. aufgelaufene Items bearbeiten
    pump();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const pump = useCallback(() => {
    if (current || visible) return;
    const next = queue.shift();
    if (!next) return;
    setCurrent(next);
    setVisible(true);
    setLoading(false);
  }, [current, visible]);

  const close = useCallback(
    (ok: boolean) => {
      if (!current) return;
      current.resolve(ok);
      setVisible(false);
      setCurrent(null);
      setLoading(false);
      // nächstes aus der Queue anzeigen
      setTimeout(pump, 0);
    },
    [current, pump]
  );

  // ESC schließt mit "Abbrechen", Enter bestätigt
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (!visible || !current) return;
      if (e.key === 'Escape') {
        e.preventDefault();
        close(false);
      } else if (e.key === 'Enter') {
        e.preventDefault();
        if (opts.showLoadingAfterConfirm) {
          setLoading(true);
          // Consumer kann während Loading async arbeiten; wir schließen sofort mit true,
          // damit der Aufrufer fortfährt. Alternativ hier NICHT sofort schließen, wenn gewünscht.
          close(true);
        } else {
          close(true);
        }
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [visible, current, close, opts.showLoadingAfterConfirm]);

  if (!visible || !current) return null;

  // === Styling identisch zu deinem FormPopup ===
  const overlay: React.CSSProperties = {
    position: 'fixed',
    inset: 0,
    background: 'rgba(0,0,0,0.5)',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 10000,
  };
  const popup: React.CSSProperties = {
    width: 520,
    minHeight: 180,
    borderRadius: '10px',
    overflow: 'hidden',
    background: '#fff',
    boxShadow: '0 4px 10px rgba(0,0,0,0.25)',
    position: 'relative',
    display: 'flex',
    flexDirection: 'column',
    padding: '10px',
  };
  const topBar: React.CSSProperties = {
    flex: '0 0 42px',
    display: 'flex',
    alignItems: 'center',
    padding: '0 16px',
    borderBottom: '1px solid #eee',
    fontWeight: 600,
  };
  const body: React.CSSProperties = {
    padding: '16px',
    flex: 1,
    display: 'flex',
    alignItems: 'center',
  };
  const actions: React.CSSProperties = {
    padding: '10px 16px',
    display: 'flex',
    justifyContent: 'flex-end',
    gap: 8,
    borderTop: '1px solid #eee',
  };
  const topBarButton: React.CSSProperties = {
    marginLeft: 'auto',
    border: 'none',
    background: 'transparent',
    fontSize: '24px',
    cursor: 'pointer',
    lineHeight: 1,
  };

  return ReactDOM.createPortal(
    <div style={overlay} onClick={() => close(false)}>
      <div style={popup} onClick={(e) => e.stopPropagation()}>
        <div style={topBar}>
          {opts.title}
          <button
            style={topBarButton}
            title="Schließen"
            onClick={() => close(false)}
            aria-label="close"
          >
            ×
          </button>
        </div>

        {loading && <LinearProgress />}

        <div style={body}>
          <div>{opts.message}</div>
        </div>

        <div style={actions}>
          <Button
            onClick={() => close(false)}
            variant="text"
          >
            {opts.cancelLabel}
          </Button>
          <Button
            onClick={() => {
              if (opts.showLoadingAfterConfirm) setLoading(true);
              close(true);
            }}
            variant="contained"
            color={opts.danger ? 'error' : 'primary'}
          >
            {opts.confirmLabel}
          </Button>
        </div>
      </div>
    </div>,
    document.getElementById('popup-root') as HTMLElement
  );
};

export default ConfirmPopup;

/**
 * Optionaler, typsicherer Helper statt window.any:
 * await askConfirm({...})
 */
export function askConfirm(options: ConfirmOptions) {
  return window.confirmPopup(options);
}
