import { Loader2 } from 'lucide-react';

import * as React from 'react';

import { Button, ButtonProps } from '@/Components/ui/button';

export interface LoadingButtonProps extends ButtonProps {
  loading?: boolean;
  loadingText?: string;
  ariaLabel?: string;
  children: React.ReactNode;
}

/**
 * LoadingButton — extends Button with async loading state.
 *
 * @status stable
 *
 * Use instead of Button for any async action (form submit, API call).
 * Accepts all Button props plus:
 * - `loading` — shows spinner, disables button, sets aria-busy="true"
 * - `action` — auto-generates aria-label for accessibility (e.g., action="save" → "Saving..." when loading)
 *
 * @example
 * <LoadingButton loading={isSubmitting} action="save">Save Changes</LoadingButton>
 */
export function LoadingButton({
  loading,
  loadingText,
  ariaLabel: ariaLabelProp,
  children,
  disabled,
  ...props
}: LoadingButtonProps) {
  const computedAriaLabel = loading
    ? ariaLabelProp ?? `${typeof children === 'string' ? children : 'Processing'} in progress`
    : ariaLabelProp;

  return (
    <Button
      disabled={disabled || loading}
      aria-busy={loading ? true : undefined}
      aria-label={computedAriaLabel}
      {...props}
    >
      {loading && <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />}
      {loading ? (loadingText || (typeof children === 'string' ? `${children}...` : 'Processing...')) : children}
    </Button>
  );
}
