/**
 * TEAM: frontend_infra
 *
 * @flow
 */

import * as React from "react";

import {countries} from "./constants/AddressOptionConstants.generated";
import Flag from "./Flag";
import SearchableSelectInput from "./select/SearchableSelectInput";
import {type Size} from "./sizes";
import LatitudeFlagImageSrc from "./latitude_flag.svg";

const PREFERRED_COUNTRIES = Object.keys(countries);
const DEFAULT_COUNTRY = "United States";
type Country = $Keys<typeof countries>;
const PATH = "https://assets.flexport.com/flags/svg/1/";
const EXTENSION = ".svg";
type CountrySelectorProps = {|
  /** the current selected value of the select input */
  +value?: string | null,
  /** the size of the input */
  +size?: Size,
  /** called when the value of the textinput changes, passes value and countryCode */
  +onChange: (string | null) => void,
  /** the placeholder text that will be displayed when the input is empty */
  +placeholder?: string,
  /** whether the input is disabled or not */
  +disabled?: boolean,
  /** whether the input is invalid or not */
  +isInvalid?: boolean,
  /** whether the input is prefilled or not */
  +isPrefilled?: boolean,
  /** list of `ISO 3166-1 aplpha` 2 character country codes to display as options */
  +countryOptions?: $ReadOnlyArray<Country>,
  /** the field from "countries" to use as the selected value, defaulting to "name" */
  +valueField?: "name" | "code",
|};

/**
 * @category Data entry
 * @short Use CountrySelector to search and select countries
 * @brandStatus V3
 * @status Beta
 * The CountrySelector component has dropdown and search functionality to
 * find and display a country and its flag.
 * */
export default function CountrySelector({
  onChange,
  size = "m",
  disabled = false,
  isInvalid = false,
  isPrefilled = false,
  countryOptions = PREFERRED_COUNTRIES,
  value = DEFAULT_COUNTRY,
  valueField = "name",
}: CountrySelectorProps): React.Node {
  const options = countryOptions.map(country => ({
    label: `${countries[country].name}`,
    value: countries[country][valueField],
    customView: (
      <div
        style={{
          padding: "8px",
        }}
      >
        <Flag countryCode={country} maxWidth={16} />
        {` ${countries[country].name}`}
      </div>
    ),
    imageSrc: `${PATH}${country}${EXTENSION}`,
  }));

  return (
    <SearchableSelectInput
      disabled={disabled}
      isInvalid={isInvalid}
      isPrefilled={isPrefilled}
      isNullable={true}
      options={options}
      value={value || ""}
      onChange={onChange}
      placeholder={value || ""}
      showImage={true}
      size={size}
      placeholderPrefix={LatitudeFlagImageSrc}
    />
  );
}
