/**
 * CurrencyInput widget component with formatting and locale support.
 *
 * ⚠️ AUTO-GENERATED BY PRISM - DO NOT EDIT
 */

import { useState, useEffect, type ChangeEvent } from 'react';
import type { WidgetBaseProps } from '../types';

interface CurrencyInputProps extends WidgetBaseProps<number | null> {
  currency?: string;
  locale?: string;
  min?: number;
  max?: number;
}

export function CurrencyInput({
  name,
  value,
  onChange,
  label,
  description,
  placeholder,
  required,
  disabled,
  error,
  className,
  currency = 'USD',
  locale = 'en-US',
  min,
  max,
}: CurrencyInputProps): JSX.Element {
  const [displayValue, setDisplayValue] = useState('');
  const [isFocused, setIsFocused] = useState(false);

  // Format number for display
  const formatCurrency = (num: number | null): string => {
    if (num === null || num === undefined) return '';
    return new Intl.NumberFormat(locale, {
      style: 'currency',
      currency,
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }).format(num);
  };

  // Update display when value changes externally
  useEffect(() => {
    if (!isFocused) {
      setDisplayValue(value !== null ? formatCurrency(value) : '');
    }
  }, [value, isFocused, currency, locale]);

  const handleFocus = () => {
    setIsFocused(true);
    // Show raw number when focused
    setDisplayValue(value !== null ? String(value) : '');
  };

  const handleBlur = () => {
    setIsFocused(false);
    // Parse and format on blur
    const parsed = parseFloat(displayValue.replace(/[^\d.-]/g, ''));
    if (!isNaN(parsed)) {
      onChange(parsed);
      setDisplayValue(formatCurrency(parsed));
    } else {
      onChange(null);
      setDisplayValue('');
    }
  };

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    const raw = e.target.value;
    setDisplayValue(raw);
    // Update value in real-time for controlled components
    const parsed = parseFloat(raw.replace(/[^\d.-]/g, ''));
    if (!isNaN(parsed)) {
      onChange(parsed);
    }
  };

  return (
    <div className={className}>
      {label && (
        <label htmlFor={name} className="label">
          {label}
          {required && <span className="text-red-500 ml-1">*</span>}
        </label>
      )}
      <input
        id={name}
        type="text"
        inputMode="decimal"
        name={name}
        value={displayValue}
        onChange={handleChange}
        onFocus={handleFocus}
        onBlur={handleBlur}
        placeholder={placeholder ?? formatCurrency(0)}
        disabled={disabled}
        required={required}
        className={error ? 'input-error' : 'input'}
        aria-invalid={!!error}
        aria-describedby={description ? `${name}-desc` : error ? `${name}-error` : undefined}
      />
      {description && !error && (
        <p id={`${name}-desc`} className="mt-1.5 text-sm text-nordic-500">{description}</p>
      )}
      {error && (
        <p id={`${name}-error`} className="mt-1.5 text-sm text-red-600">
          {error}
        </p>
      )}
    </div>
  );
}
