"use client";

import { useMemo } from "react";
import PhoneInput, { CountryData } from "react-phone-input-2";
import clsx from "clsx";
import styles from "./PhoneField.module.css";

type PhoneFieldProps = {
  id?: string;
  label?: string;
  value: string;
  onChange: (value: string, data: CountryData) => void;
  onBlur?: () => void;
  error?: string;
  required?: boolean;
  disabled?: boolean;
  placeholder?: string;
  containerClassName?: string;
};

export function PhoneField({
  id = "phone",
  label = "Phone Number",
  value,
  onChange,
  onBlur,
  error,
  required,
  disabled,
  placeholder = "Phone number",
  containerClassName,
}: PhoneFieldProps) {
  const hasValue = useMemo(() => value?.trim().length > 0, [value]);

  // Show + sign only when no country is selected (no value or very short value)
  const showPlus = useMemo(() => !value || value.length <= 1, [value]);

  return (
    <div
      className={clsx(
        styles.wrapper,
        hasValue && styles.hasValue,
        showPlus && styles.noCountry,
        containerClassName
      )}
    >
      {label && (
        <label htmlFor={id} className={styles.label}>
          {label}
          {required ? " *" : ""}
        </label>
      )}
      <PhoneInput
        country={""}
        preferredCountries={["us", "pa", "gb"]}
        value={value}
        onChange={onChange}
        onBlur={onBlur}
        inputProps={{
          id,
          name: id,
          required,
          disabled,
          autoComplete: "tel",
          placeholder: placeholder
        }}
        containerClass={styles.container}
        buttonClass={styles.country}
        inputClass={styles.input}
        dropdownClass={styles.dropdown}
        searchClass={styles.search}
        specialLabel={""}
        disableDropdown={disabled}
        enableSearch
        searchPlaceholder="Search country"
        disableSearchIcon
        disableCountryCode={false}
        enableAreaCodes={false}
      />
      {error && (
        <p role="alert" className={styles.error}>
          {error}
        </p>
      )}
    </div>
  );
}