import { parsePhoneNumberWithError, isValidPhoneNumber as libIsValidPhoneNumber, formatIncompletePhoneNumber, CountryCode } from 'libphonenumber-js';

export const formatPhoneNumber = (phoneNumber: string, defaultCountry: CountryCode = 'ET'): string => {
  if (!phoneNumber) return '';
  
  try {
    const parsedNumber = parsePhoneNumberWithError(phoneNumber, defaultCountry);
    if (parsedNumber && parsedNumber.isValid()) {
        const e164Formatted = parsedNumber.format('E.164');
      return parsedNumber.format('E.164'); // Returns format like +251911234567
    }
  } catch (error) {
    try {
      const formatted = formatIncompletePhoneNumber(phoneNumber, defaultCountry);
      if (formatted) {
        return formatted;
      }
    } catch (formatError) {
      console.warn('Failed to format phone number:', phoneNumber, formatError);
    }
  }
  return phoneNumber;
};

export const isValidPhoneNumber = (phoneNumber: string, defaultCountry: CountryCode = 'ET'): boolean => {
  if (!phoneNumber) return false;
  
  try {
    return libIsValidPhoneNumber(phoneNumber, defaultCountry);
  } catch (error) {
    return false;
  }
};

export const parsePhoneNumberDetails = (phoneNumber: string, defaultCountry: CountryCode = 'ET') => {
  if (!phoneNumber) return null;
  
  try {
    const parsedNumber = parsePhoneNumberWithError(phoneNumber, defaultCountry);
    if (parsedNumber && parsedNumber.isValid()) {
      return {
        country: parsedNumber.country,
        countryCallingCode: parsedNumber.countryCallingCode,
        nationalNumber: parsedNumber.nationalNumber,
        international: parsedNumber.format('INTERNATIONAL'),
        e164: parsedNumber.format('E.164'),
        national: parsedNumber.format('NATIONAL'),
        rfc3966: parsedNumber.format('RFC3966'),
        isValid: true
      };
    }
  } catch (error) {
    console.warn('Failed to parse phone number:', phoneNumber, error);
  }
  
  return null;
};
