'use client';
import { ChangeEvent, FunctionComponent } from 'react';
import TextField, { TextFieldProps } from '@mui/material/TextField';
import { digitsOnly } from '@/utils';

/** Iranian mobile numbers are 11 digits, e.g. 09123456789. */
export const IRAN_MOBILE_LENGTH = 11;

/** True when `value` is a well-formed Iranian mobile number (11 digits starting 09). */
export function isIranianMobile(value: string): boolean {
  return /^09\d{9}$/.test(value);
}

/**
 * Masks a mobile number for a "code sent to …" echo, keeping the first 4 and last 4 digits
 * (e.g. `09120001234` → `0912•••1234`). Short/partial input is returned unchanged.
 */
export function maskIranMobile(value: string): string {
  if (value.length < 8) return value;
  return `${value.slice(0, 4)}•••${value.slice(-4)}`;
}

export interface PhoneNumberFieldProps extends Omit<TextFieldProps, 'onChange' | 'value' | 'type'> {
  /** Controlled value — normalized ASCII digits, no formatting. */
  value: string;
  /** Emits the normalized digit string (Persian/Arabic digits converted, capped at 11). */
  onChange: (value: string) => void;
}

/**
 * Iranian mobile-number field. Normalizes Persian/Arabic digits to ASCII, strips
 * non-digits, and caps length. Forces LTR digit entry so it stays correct inside the
 * RTL (`fa`) layout. Text (label/placeholder/helperText) is passed in by the caller.
 * @component PhoneNumberField
 */
const PhoneNumberField: FunctionComponent<PhoneNumberFieldProps> = ({ value, onChange, slotProps, ...rest }) => {
  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    onChange(digitsOnly(event.target.value).slice(0, IRAN_MOBILE_LENGTH));
  };

  return (
    <TextField
      value={value}
      onChange={handleChange}
      slotProps={{
        htmlInput: {
          dir: 'ltr',
          inputMode: 'numeric',
          maxLength: IRAN_MOBILE_LENGTH,
          // Offers the user's own number from the browser/keyboard's saved contact info.
          autoComplete: 'tel',
          style: { textAlign: 'start' },
        },
        ...slotProps,
      }}
      {...rest}
    />
  );
};

export default PhoneNumberField;
