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

export interface CountrySelectProps extends Omit<SelectProps, 'options'> {
  /** 是否只显示常用国家 */
  popularOnly?: boolean;
  /** 自定义国家列表 */
  countries?: CountryData[];
  /** 是否显示国旗 */
  showFlag?: boolean;
  /** 是否显示国家代码 */
  showCode?: boolean;
  /** 语言: 'zh' 显示中文, 'en' 显示英文, 默认跟随系统 */
  language?: 'zh' | 'en';
}

const CountrySelect: React.FC<CountrySelectProps> = ({
  popularOnly = false,
  countries,
  showFlag = true,
  showCode = true,
  language,
  ...restProps
}) => {
  const intl = useIntl();

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

  // 获取国家列表
  const countryList = useMemo(() => {
    if (countries) return countries;
    if (popularOnly) return getPopularCountries();
    return getSortedCountries();
  }, [countries, popularOnly]);

  // 生成选项
  const options = useMemo(() => {
    const popularCountries = getPopularCountries();
    const popularCodes = new Set(popularCountries.map((c) => c.code));

    // 如果不是只显示常用国家，需要分组
    if (!popularOnly && !countries) {
      return [
        {
          label: isZh ? '常用国家/地区' : 'Popular Countries',
          options: popularCountries.map((country) => ({
            label: (
              <span>
                {showFlag && <span style={{ marginRight: 8 }}>{country.flag}</span>}
                {isZh ? country.nameZh : country.nameEn}
                {showCode && (
                  <span style={{ color: '#999', marginLeft: 8 }}>({country.code})</span>
                )}
              </span>
            ),
            value: country.code,
            searchText: `${country.nameZh} ${country.nameEn} ${country.code}`,
          })),
        },
        {
          label: isZh ? '全部国家/地区' : 'All Countries',
          options: COUNTRIES.filter((c) => !popularCodes.has(c.code)).map((country) => ({
            label: (
              <span>
                {showFlag && <span style={{ marginRight: 8 }}>{country.flag}</span>}
                {isZh ? country.nameZh : country.nameEn}
                {showCode && (
                  <span style={{ color: '#999', marginLeft: 8 }}>({country.code})</span>
                )}
              </span>
            ),
            value: country.code,
            searchText: `${country.nameZh} ${country.nameEn} ${country.code}`,
          })),
        },
      ];
    }

    // 不分组的情况
    return countryList.map((country) => ({
      label: (
        <span>
          {showFlag && <span style={{ marginRight: 8 }}>{country.flag}</span>}
          {isZh ? country.nameZh : country.nameEn}
          {showCode && <span style={{ color: '#999', marginLeft: 8 }}>({country.code})</span>}
        </span>
      ),
      value: country.code,
      searchText: `${country.nameZh} ${country.nameEn} ${country.code}`,
    }));
  }, [countryList, isZh, showFlag, showCode, popularOnly, countries]);

  return (
    <Select
      showSearch
      optionFilterProp="searchText"
      filterOption={(input, option) => {
        const searchText = (option as any)?.searchText || '';
        return searchText.toLowerCase().includes(input.toLowerCase());
      }}
      placeholder={isZh ? '请选择国家/地区' : 'Select country/region'}
      options={options}
      {...restProps}
    />
  );
};

export default CountrySelect;
