import React from 'react';
import {useEffect} from 'react';
import {useState} from 'react';
import {findErrorByName} from './named_error';

export function CountryDropdown(props) {
  const {countries, countryChanged, selectedCountry, required, restrictedCountries, errors, setErrors} = props;

  const ERROR_MESSAGE = 'Due to shipping restrictions, we currently can not ship to Ukraine, or Russia. We apologize for the inconvenience.';

  const onChange = (args) => {
    let error = findErrorByName(errors, 'country');
    if (error && error.message === ERROR_MESSAGE) {
        errors.splice(errors.indexOf(error), 1);
    }
    countryChanged(args);
  };

  let optionElements = [];
  for (const country of countries) {
    const code = country[0];
    const name = country[1];
    optionElements.push(<option key={code} value={code}>{name}</option>);
  }

  let classes=['field'];
  if (required) {
    classes.push('required');
  }

  let restricted = restrictedCountries.includes(selectedCountry.toUpperCase());
  let restricted_notice_style = {'display': 'block'};
  if (restricted) {
    classes.push('error');
    restricted_notice_style['color'] = 'red';
  } else {
    delete restricted_notice_style.color;
  }

  return (
    <React.Fragment>
      <select id="country" name="country" className={classes.join(' ')} onChange={onChange} value={selectedCountry}>
        {optionElements}
      </select>
      <span style={restricted_notice_style}>
        {ERROR_MESSAGE}
      </span>
    </React.Fragment>
  );
}
