import React from 'react';
import { Form } from 'antd';
import type { RuleObject } from 'rc-field-form/lib/interface';
import PhoneInput from 'antd-phone-input';

import countries from 'i18n-iso-countries';
import enLocale from 'i18n-iso-countries/langs/en.json';
countries.registerLocale(enLocale);

interface InputPhoneProps {
  name: string;
  label: string;
  disabled?: boolean;
  rules?: RuleObject[];
  defaultCountry?: string;
  enableSearch?: boolean;
  [key: string]: unknown;
}

const InputPhone: React.FC<InputPhoneProps> = ({
  name,
  label,
  disabled = false,
  rules = [],
  defaultCountry = 'in',
  enableSearch = false,
  ...restProps
}) => {
  // returns both the formatted number and the country name
  const formatPhoneValue = (value: any): { number: string; country: string } => {
    if (!value) return { number: '', country: '' };
    const { countryCode, areaCode, phoneNumber, isoCode } = value;
    // build full number string
    const fullNumber = areaCode ? `+${countryCode}${areaCode}${phoneNumber}` : `+${countryCode}${phoneNumber}`;
    // lookup country name via i18n-iso-countries
    const countryName = isoCode ? countries.getName(isoCode.toUpperCase(), 'en') || '' : '';
    return { number: fullNumber, country: countryName };
  };

  return (
    <Form.Item
      label={label}
      name={name}
      rules={rules}
      getValueFromEvent={(value) => formatPhoneValue(value)}
    >
      <PhoneInput
        disabled={disabled}
        country={defaultCountry}
        enableSearch={enableSearch}
        enableArrow
        disableParentheses
        {...restProps}
      />
    </Form.Item>
  );
};

export default InputPhone;