"use client";

import * as React from "react";

import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
  InputGroupText,
} from "@/components/ui/input-group";
import { cn } from "@/lib/utils";

const SA_COUNTRY_CODE = "+966";
/** Saudi national numbers are 9 digits (5XXXXXXXX for mobiles) */
const MAX_NATIONAL_DIGITS = 9;

interface PhoneInputProps extends Omit<
  React.ComponentProps<"input">,
  "value" | "onChange" | "type" | "dir"
> {
  /** Full E.164 value, e.g. "+966512345678" — empty string when unset */
  value?: string;
  /** Emits the full E.164 value ("+966" + digits), or "" when cleared */
  onChange?: (value: string) => void;
  /** Extra classes for the outer InputGroup */
  className?: string;
}

/**
 * Saudi phone number input with a fixed +966 country code.
 *
 * - Accepts digits only, strips a leading 0 (05X… → 5X…), caps at 9 digits.
 * - Value contract is full E.164 ("+9665XXXXXXXX") so it can go straight into
 *   API payloads; internally only the national part is shown.
 * - Phone numbers are compound LTR content (design RTL rule 5) — the whole
 *   group is forced `dir="ltr"` so "+966" stays before the digits in Arabic.
 */
function PhoneInput({
  value = "",
  onChange,
  className,
  ...props
}: PhoneInputProps) {
  const national = value.startsWith(SA_COUNTRY_CODE)
    ? value.slice(SA_COUNTRY_CODE.length)
    : value.replace(/\D/g, "");

  function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
    let digits = event.target.value.replace(/\D/g, "");
    // Local convention 05XXXXXXXX → international 5XXXXXXXX
    digits = digits.replace(/^0+/, "");
    digits = digits.slice(0, MAX_NATIONAL_DIGITS);
    onChange?.(digits ? `${SA_COUNTRY_CODE}${digits}` : "");
  }

  return (
    <InputGroup dir="ltr" className={cn(className)}>
      <InputGroupAddon align="inline-start">
        {/* Numeric font for the code, per the numbers-render-in-Inter rule */}
        <InputGroupText className="font-numeric text-main-text">
          {SA_COUNTRY_CODE}
        </InputGroupText>
      </InputGroupAddon>
      <InputGroupInput
        type="tel"
        inputMode="tel"
        autoComplete="tel-national"
        className="font-numeric"
        value={national}
        onChange={handleChange}
        {...props}
      />
    </InputGroup>
  );
}

export { PhoneInput, SA_COUNTRY_CODE };
