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

interface CurrencyInputProps {
  value: number; // Value in cents (integer)
  onChange: (cents: number) => void;
  disabled?: boolean;
  required?: boolean;
  placeholder?: string;
  className?: string;
  min?: number;
  max?: number;
}

/**
 * Currency input where digits represent cents.
 * Only accepts integer input (0-9), no decimal points.
 * Allows normal text selection and editing.
 *
 * Examples:
 * - Type "5" → $0.05
 * - Type "50" → $0.50
 * - Type "500" → $5.00
 * - Type "1234" → $12.34
 */
const CurrencyInput: React.FC<CurrencyInputProps> = ({
  value,
  onChange,
  disabled = false,
  required = false,
  placeholder = '$0.00',
  className = '',
  min,
  max,
}) => {
  const inputRef = useRef<HTMLInputElement>(null);
  const [displayValue, setDisplayValue] = useState('');

  // Format cents as dollars string (e.g., 1234 → "$12.34")
  const formatCentsAsDollars = (cents: number): string => {
    if (cents === 0) return '';
    const dollars = cents / 100;
    return `$${dollars.toFixed(2)}`;
  };

  // Extract just the digits from a string
  const extractDigits = (str: string): string => {
    return str.replace(/\D/g, '');
  };

  // Sync display value when external value changes
  useEffect(() => {
    setDisplayValue(formatCentsAsDollars(value));
  }, [value]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const input = e.target.value;

    // Extract only digits
    const digits = extractDigits(input);

    // Convert to cents (the digits ARE the cents value)
    let cents = digits ? parseInt(digits, 10) : 0;

    // Enforce max if specified
    if (max !== undefined && cents > max) {
      cents = max;
    }

    onChange(cents);

    // Update display immediately with formatted value
    setDisplayValue(formatCentsAsDollars(cents));
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    // Allow: navigation, selection, delete, backspace, tab, escape, enter
    const allowedKeys = [
      'Backspace', 'Delete', 'Tab', 'Escape', 'Enter',
      'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown',
      'Home', 'End'
    ];

    if (allowedKeys.includes(e.key)) {
      return; // Let these through
    }

    // Allow Ctrl/Cmd + A, C, V, X (select all, copy, paste, cut)
    if ((e.ctrlKey || e.metaKey) && ['a', 'c', 'v', 'x'].includes(e.key.toLowerCase())) {
      return;
    }

    // Only allow digits 0-9
    if (!/^[0-9]$/.test(e.key)) {
      e.preventDefault();
    }
  };

  const handleFocus = (e: React.FocusEvent<HTMLInputElement>) => {
    // Select all text for easy replacement
    setTimeout(() => {
      e.target.select();
    }, 0);
  };

  const handleBlur = () => {
    // Extract digits and reparse to enforce constraints
    const digits = extractDigits(displayValue);
    let cents = digits ? parseInt(digits, 10) : 0;

    // Enforce min on blur if specified
    if (min !== undefined && cents < min && cents > 0) {
      cents = min;
      onChange(cents);
    }

    // Enforce max on blur if specified
    if (max !== undefined && cents > max) {
      cents = max;
      onChange(cents);
    }

    // Reformat display
    setDisplayValue(formatCentsAsDollars(cents));
  };

  const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
    e.preventDefault();
    const pastedText = e.clipboardData.getData('text');
    const digits = extractDigits(pastedText);

    if (digits) {
      let cents = parseInt(digits, 10);

      if (max !== undefined && cents > max) {
        cents = max;
      }

      onChange(cents);
      setDisplayValue(formatCentsAsDollars(cents));
    }
  };

  return (
    <input
      ref={inputRef}
      type="text"
      inputMode="numeric"
      value={displayValue}
      onChange={handleChange}
      onKeyDown={handleKeyDown}
      onFocus={handleFocus}
      onBlur={handleBlur}
      onPaste={handlePaste}
      disabled={disabled}
      required={required}
      placeholder={placeholder}
      className={className}
      autoComplete="off"
      autoCorrect="off"
      autoCapitalize="off"
      spellCheck={false}
    />
  );
};

export default CurrencyInput;
