import { useEffect, useState, type ReactNode } from 'react';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@rutatiina/ui/components/ui/alert-dialog';
import { useTrans } from '@rutatiina/ui/lib/translations';

export type ConfirmOptions = {
  title: string;
  description?: ReactNode;
  confirmLabel?: string;
  cancelLabel?: string;
  /** Styles the action as destructive, for discarding or replacing work. */
  destructive?: boolean;
};

type Request = ConfirmOptions & { resolve: (answer: boolean) => void };

let enqueue: ((request: Request) => void) | null = null;

/**
 * The themed replacement for the browser confirm box: resolves true when the person
 * chooses the action, false when they cancel, press Escape or click outside.
 * Never open the browser's own alert, confirm or prompt boxes in this application.
 */
export function confirm(options: ConfirmOptions): Promise<boolean> {
  return new Promise((resolve) => {
    if (!enqueue) {
      // The provider is mounted for every page; without it, err on the side of staying.
      resolve(false);
      return;
    }
    enqueue({ ...options, resolve });
  });
}

export function useConfirm(): typeof confirm {
  return confirm;
}

/** Holds the one confirmation dialog the whole application shares. */
export function ConfirmProvider({ children }: { children: ReactNode }) {
  const __ = useTrans();
  const [queue, setQueue] = useState<Request[]>([]);
  const current = queue[0];

  useEffect(() => {
    enqueue = (request) => setQueue((pending) => [...pending, request]);
    return () => {
      enqueue = null;
    };
  }, []);

  const answer = (value: boolean) => {
    if (!current) return;
    current.resolve(value);
    setQueue((pending) => pending.slice(1));
  };

  return (
    <>
      {children}
      <AlertDialog
        open={!!current}
        onOpenChange={(open) => {
          if (!open) answer(false);
        }}
      >
        {current && (
          <AlertDialogContent
            className="md:max-w-[420px]"
            onOpenAutoFocus={(event) => {
              // Start on the safe choice, so Enter never discards work by accident.
              event.preventDefault();
              (event.currentTarget as HTMLElement)
                .querySelector<HTMLElement>('[data-slot="alert-dialog-cancel"]')
                ?.focus();
            }}
          >
            <AlertDialogHeader>
              <AlertDialogTitle>{current.title}</AlertDialogTitle>
              <AlertDialogDescription
                className={current.description ? undefined : 'sr-only'}
              >
                {current.description ?? current.title}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel onClick={() => answer(false)}>
                {current.cancelLabel ?? __('Cancel')}
              </AlertDialogCancel>
              <AlertDialogAction
                variant={current.destructive ? 'destructive' : 'primary'}
                onClick={() => answer(true)}
              >
                {current.confirmLabel ?? __('Continue')}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        )}
      </AlertDialog>
    </>
  );
}
