import { useState, useId } from 'react';
import { agorotToShekels, shekelsToAgorot, formatAgorotShekels } from '@/lib/money';
import { cn } from '@/lib/cn';

interface AdminMoneyInputProps {
  name: string;
  label: string;
  /** Current value in agorot from server (e.g. 29900 = ₪299). */
  valueAgorot?: number;
  onChange: (agorot: number) => void;
  /** Min allowed in agorot (inclusive). */
  minAgorot?: number;
  /** Max allowed in agorot (e.g. platform fee ceiling). */
  maxAgorot?: number;
  required?: boolean;
  disabled?: boolean;
  className?: string;
}

/**
 * Admin money input: user types shekel values; submits agorot (×100).
 * Live preview '= ₪X.XX' for verification.
 */
export function AdminMoneyInput({
  name,
  label,
  valueAgorot,
  onChange,
  minAgorot,
  maxAgorot,
  required,
  disabled,
  className,
}: AdminMoneyInputProps) {
  const [shekelValue, setShekelValue] = useState<string>(
    valueAgorot != null ? agorotToShekels(valueAgorot).toFixed(2) : '',
  );
  const previewId = useId();

  const parsed = parseFloat(shekelValue);
  const agorot = Number.isFinite(parsed) ? shekelsToAgorot(parsed) : null;
  const previewText = agorot != null ? '= ' + formatAgorotShekels(agorot) : '';

  function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    const raw = e.target.value;
    setShekelValue(raw);
    const p = parseFloat(raw);
    if (Number.isFinite(p)) onChange(shekelsToAgorot(p));
  }

  return (
    <div className={cn('flex flex-col gap-1', className)}>
      <label htmlFor={name} className="text-sm font-medium">
        {label}
      </label>
      <div className="relative flex items-center">
        <span className="text-muted-foreground absolute start-3 select-none" aria-hidden>
          ₪
        </span>
        <input
          id={name}
          name={name}
          type="number"
          step="0.01"
          min={minAgorot != null ? agorotToShekels(minAgorot) : undefined}
          max={maxAgorot != null ? agorotToShekels(maxAgorot) : undefined}
          value={shekelValue}
          onChange={handleChange}
          required={required}
          disabled={disabled}
          aria-describedby={previewId}
          className="border-input bg-background focus-visible:ring-ring w-full rounded-md border py-2 ps-7 pe-3 text-sm focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none"
        />
      </div>
      {previewText && (
        <p id={previewId} className="text-muted-foreground text-xs" aria-live="polite">
          {previewText}
        </p>
      )}
    </div>
  );
}
