'use client';

import * as React from 'react';
import { useTranslations } from 'next-intl';
import { cn } from '@/lib/utils';

export interface PhoneInputProps
  extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'type' | 'inputMode' | 'dir'> {
  label?: string;
  hint?: string;
  error?: string;
  countryCode?: string;
}

/**
 * Shared phone input.
 *  - `dir="ltr"` so digits render correctly under RTL.
 *  - Localized placeholder via `fields.phone_placeholder_e164` so AR users see
 *    Eastern-Arabic numerals while EN users see Latin numerals.
 *  - Decorative `+20` country-code prefix flagged `aria-hidden`; the real label
 *    is announced via `fields.phone_country_code_label`.
 */
export const PhoneInput = React.forwardRef<HTMLInputElement, PhoneInputProps>(
  ({ className, label, hint, error, id, countryCode = '+20', ...props }, ref) => {
    const t = useTranslations('fields');
    const inputId = id ?? (label ? `${label.toLowerCase().replace(/\s+/g, '-')}-phone` : 'phone');

    return (
      <div className="flex flex-col gap-1.5">
        {label ? (
          <label htmlFor={inputId} className="text-sm font-medium text-neutral-700">
            {label}
          </label>
        ) : null}
        <div className="relative">
          <span
            aria-hidden="true"
            className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-sm text-neutral-500"
            dir="ltr"
          >
            {countryCode}
          </span>
          <span className="sr-only">{t('phone_country_code_label')}</span>
          <input
            ref={ref}
            id={inputId}
            dir="ltr"
            type="tel"
            inputMode="tel"
            autoComplete="tel"
            placeholder={t('phone_placeholder_e164')}
            className={cn(
              'w-full rounded-md border bg-white py-2.5 pr-3 pl-14 text-sm text-neutral-900 placeholder:text-neutral-400 transition-colors outline-none',
              'focus:border-primary-600 focus:ring-2 focus:ring-primary-100',
              error ? 'border-danger focus:border-danger focus:ring-danger/20' : 'border-neutral-300',
              props.disabled ? 'cursor-not-allowed bg-neutral-50 text-neutral-400' : '',
              className,
            )}
            aria-invalid={error ? 'true' : undefined}
            aria-describedby={error ? `${inputId}-error` : hint ? `${inputId}-hint` : undefined}
            {...props}
          />
        </div>
        {hint && !error ? (
          <p id={`${inputId}-hint`} className="text-xs text-neutral-500">
            {hint}
          </p>
        ) : null}
        {error ? (
          <p id={`${inputId}-error`} role="alert" className="text-xs text-danger">
            {error}
          </p>
        ) : null}
      </div>
    );
  },
);

PhoneInput.displayName = 'PhoneInput';
