import { Select } from 'antd';
import type { SelectProps } from 'antd';
import { useIntl } from '@umijs/max';
import React, { useMemo } from 'react';
import { getSortedCountries, getPopularCountries } from './countries';
import type { CountryData } from './countries';

export interface PhonePrefixSelectProps extends Omit<SelectProps, 'options'> {
  /** 是否只显示常用国家的区号 */
  popularOnly?: boolean;
  /** 是否显示国旗 */
  showFlag?: boolean;
  /** 是否显示国家名称 */
  showCountryName?: boolean;
  /** 语言: 'zh' 显示中文, 'en' 显示英文, 默认跟随系统 */
  language?: 'zh' | 'en';
}

const PhonePrefixSelect: React.FC<PhonePrefixSelectProps> = ({
  popularOnly = false,
  showFlag = true,
  showCountryName = true,
  language,
  ...restProps
}) => {
  const intl = useIntl();

  // 判断当前语言
  const isZh = language === 'zh' || (!language && intl.locale?.startsWith('zh'));

  // 获取国家列表并去重区号
  const options = useMemo(() => {
    const countryList = popularOnly ? getPopularCountries() : getSortedCountries();

    // 按区号分组，保留第一个国家作为显示
    const phoneCodeMap = new Map<string, CountryData>();
    countryList.forEach((country) => {
      if (!phoneCodeMap.has(country.phoneCode)) {
        phoneCodeMap.set(country.phoneCode, country);
      }
    });

    const popularCountries = getPopularCountries();
    const popularPhoneCodes = new Set(popularCountries.map((c) => c.phoneCode));

    // 如果不是只显示常用国家，需要分组
    if (!popularOnly) {
      const popularOptions: any[] = [];
      const otherOptions: any[] = [];

      phoneCodeMap.forEach((country, phoneCode) => {
        const option = {
          label: (
            <span>
              {showFlag && <span style={{ marginRight: 6 }}>{country.flag}</span>}
              <span style={{ fontWeight: 500 }}>+{phoneCode}</span>
              {showCountryName && (
                <span style={{ color: '#666', marginLeft: 8 }}>
                  {isZh ? country.nameZh : country.nameEn}
                </span>
              )}
            </span>
          ),
          value: phoneCode,
          searchText: `+${phoneCode} ${country.nameZh} ${country.nameEn} ${country.code}`,
        };

        if (popularPhoneCodes.has(phoneCode)) {
          popularOptions.push(option);
        } else {
          otherOptions.push(option);
        }
      });

      return [
        {
          label: isZh ? '常用' : 'Popular',
          options: popularOptions,
        },
        {
          label: isZh ? '全部' : 'All',
          options: otherOptions,
        },
      ];
    }

    // 不分组的情况
    return Array.from(phoneCodeMap.entries()).map(([phoneCode, country]) => ({
      label: (
        <span>
          {showFlag && <span style={{ marginRight: 6 }}>{country.flag}</span>}
          <span style={{ fontWeight: 500 }}>+{phoneCode}</span>
          {showCountryName && (
            <span style={{ color: '#666', marginLeft: 8 }}>
              {isZh ? country.nameZh : country.nameEn}
            </span>
          )}
        </span>
      ),
      value: phoneCode,
      searchText: `+${phoneCode} ${country.nameZh} ${country.nameEn} ${country.code}`,
    }));
  }, [popularOnly, isZh, showFlag, showCountryName]);

  return (
    <Select
      showSearch
      optionFilterProp="searchText"
      filterOption={(input, option) => {
        const searchText = (option as any)?.searchText || '';
        return searchText.toLowerCase().includes(input.toLowerCase());
      }}
      placeholder={isZh ? '区号' : 'Code'}
      options={options}
      dropdownStyle={{ minWidth: 280 }}
      {...restProps}
    />
  );
};

export default PhonePrefixSelect;
