import {COUNTRIES} from '@shared/countries';
import {getPhoneNumberMaxLength, getPhoneValues} from '@shared/utils/phone';

import {FlagKey} from './components/CountryCodeSelector';

const DEFAULT_MAX_LENGTH = 15;
const initialCountrySelected = COUNTRIES.at(0)!;

export const getDialCode = (countryCode: FlagKey) =>
  COUNTRIES.find(country => country.code === countryCode)?.dialCode || '';

export const getCountryInitialValue = (defaultValue?: string) => {
  if (!defaultValue) {
    return initialCountrySelected;
  }
  const values = getPhoneValues(
    `${!defaultValue.startsWith('+') ? '+' : ''}${defaultValue}`,
  );
  return values?.country
    ? values.country
    : COUNTRIES.find(country => country.code === defaultValue) ||
        initialCountrySelected;
};

export const getPhoneInitialValue = (defaultValue?: string) => {
  if (!defaultValue) {
    return '';
  }
  const values = getPhoneValues(
    `${!defaultValue.startsWith('+') ? '+' : ''}${defaultValue}`,
  );
  return values?.phone || '';
};

export const getPhoneMaxLength = (
  countryCode: FlagKey,
  formattedPhone: string,
) => {
  try {
    const max = getPhoneNumberMaxLength(countryCode);
    const whiteSpacesCount = (formattedPhone?.split?.(' ')?.length || 1) - 1;
    return (max || DEFAULT_MAX_LENGTH) + whiteSpacesCount;
  } catch (e) {
    return DEFAULT_MAX_LENGTH;
  }
};

export const getStripDialCodePrefix = (raw: string, code: string) => {
  const rest = raw.trimStart();
  if (code && rest.startsWith(code)) {
    return rest.slice(code.length).trimStart();
  }
  return rest;
};
