'use client';

import { useState, useCallback, useMemo, createElement } from 'react';

/* -------------------------------------------------------------------------- */
/*  useConfirmation                                                           */
/*  Hook for imperative "are you sure?" confirmation dialogs.                 */
/*                                                                            */
/*  Returns:                                                                  */
/*   - confirm(message, options?) : Promise<boolean>                          */
/*   - ConfirmationDialog         : React component to render in your tree    */
/*                                                                            */
/*  Usage:                                                                    */
/*  ```tsx                                                                    */
/*  const { confirm, ConfirmationDialog } = useConfirmation();               */
/*                                                                            */
/*  async function handleDelete() {                                           */
/*    const yes = await confirm('Delete this server?', {                      */
/*      title: 'Confirm Deletion',                                            */
/*      confirmLabel: 'Delete',                                               */
/*      variant: 'destructive',                                               */
/*    });                                                                      */
/*    if (yes) deleteServer(id);                                              */
/*  }                                                                         */
/*                                                                            */
/*  return <>{...}<ConfirmationDialog /></>;                                  */
/*  ```                                                                       */
/* -------------------------------------------------------------------------- */

export interface ConfirmationOptions {
  /** Dialog title (default: "Confirm") */
  title?: string;
  /** Label for the confirm button (default: "Confirm") */
  confirmLabel?: string;
  /** Label for the cancel button (default: "Cancel") */
  cancelLabel?: string;
  /** Visual variant for the confirm button */
  variant?: 'primary' | 'destructive';
}

interface ConfirmationState {
  open: boolean;
  message: string;
  options: Required<ConfirmationOptions>;
  resolve: ((value: boolean) => void) | null;
}

const defaultOptions: Required<ConfirmationOptions> = {
  title: 'Confirm',
  confirmLabel: 'Confirm',
  cancelLabel: 'Cancel',
  variant: 'primary',
};

export function useConfirmation() {
  const [state, setState] = useState<ConfirmationState>({
    open: false,
    message: '',
    options: defaultOptions,
    resolve: null,
  });

  const confirm = useCallback(
    (message: string, options?: ConfirmationOptions): Promise<boolean> => {
      return new Promise<boolean>((resolve) => {
        setState({
          open: true,
          message,
          options: { ...defaultOptions, ...options },
          resolve,
        });
      });
    },
    [],
  );

  const handleConfirm = useCallback(() => {
    state.resolve?.(true);
    setState((prev) => ({ ...prev, open: false, resolve: null }));
  }, [state.resolve]);

  const handleCancel = useCallback(() => {
    state.resolve?.(false);
    setState((prev) => ({ ...prev, open: false, resolve: null }));
  }, [state.resolve]);

  /**
   * Render this component somewhere in your JSX tree.
   * It renders the confirmation dialog based on current state.
   */
  const ConfirmationDialog = useMemo(() => {
    return function ConfirmationDialogInner() {
      if (!state.open) return null;

      const { title, confirmLabel, cancelLabel, variant } = state.options;

      const confirmBtnClass =
        variant === 'destructive'
          ? 'bg-destructive text-destructive-foreground hover:bg-destructive/90'
          : 'bg-primary text-primary-foreground hover:bg-primary/90';

      return createElement(
        'div',
        {
          className: 'fixed inset-0 z-50 flex items-center justify-center',
          role: 'presentation',
        },
        // Backdrop
        createElement('div', {
          className: 'fixed inset-0 bg-black/60 backdrop-blur-sm',
          onClick: handleCancel,
          'aria-hidden': 'true',
        }),
        // Panel
        createElement(
          'div',
          {
            className:
              'relative z-50 w-full max-w-md rounded-lg border bg-background p-6 shadow-lg animate-in fade-in-0 zoom-in-95 duration-200',
            role: 'alertdialog',
            'aria-modal': 'true',
            'aria-labelledby': 'confirmation-title',
            'aria-describedby': 'confirmation-message',
          },
          // Title
          createElement(
            'h2',
            {
              id: 'confirmation-title',
              className: 'text-lg font-semibold leading-none tracking-tight',
            },
            title,
          ),
          // Message
          createElement(
            'p',
            {
              id: 'confirmation-message',
              className: 'mt-3 text-sm text-muted-foreground',
            },
            state.message,
          ),
          // Buttons
          createElement(
            'div',
            { className: 'mt-6 flex justify-end gap-2' },
            createElement(
              'button',
              {
                type: 'button',
                className:
                  'inline-flex h-9 items-center justify-center rounded-md border border-input bg-background px-4 text-sm font-medium shadow-sm transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
                onClick: handleCancel,
              },
              cancelLabel,
            ),
            createElement(
              'button',
              {
                type: 'button',
                className: `inline-flex h-9 items-center justify-center rounded-md px-4 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${confirmBtnClass}`,
                onClick: handleConfirm,
                autoFocus: true,
              },
              confirmLabel,
            ),
          ),
        ),
      );
    };
  }, [state.open, state.message, state.options, handleConfirm, handleCancel]);

  return { confirm, ConfirmationDialog };
}
