/* eslint-disable react/prop-types */
import classNames from 'classnames';

function FormSelect({ field, form, options, ...props }) {
  const id = props.id || field.name;
  const label = props.label || field.name;
  const placeholder = props.placeholder || label;
  const exactLabel = ['.', '?', '!', '؟'].includes(label.charAt(label.length - 1))
    ? label.substring(0, label.length - 1)
    : label;
  const error = form.errors[field.name];
  const hasError = error && form.touched[field.name];

  return (
    <div className={props.className}>
      <label
        htmlFor={id}
        className={classNames(
          'mb-3 block text-sm font-medium',
          hasError ? 'text-red-500' : 'text-gray-700',
          { 'after:mx-1 after:text-red-500 after:content-["*"]': props.required },
          { 'after:mx-1 after:text-green-500 after:content-["(اختیاری)"]': !props.required },
          { 'text-red-500 ': hasError }
        )}
      >
        {`${exactLabel} :`}
      </label>
      <select
        {...props}
        {...field}
        id={id}
        data-testid={`${field.name}-field`}
        placeholder={placeholder}
        onChange={field.onChange}
        onBlur={field.onBlur}
        className={classNames(
          'block w-full rounded-md border px-4 py-2 shadow-sm focus:outline-none sm:text-sm',
          'text-center placeholder:text-center',
          { 'text-red-400 placeholder:text-red-400': hasError },
          { 'border-red-400 bg-red-50 focus:border-red-500 focus:ring-red-500': hasError },
          { 'border-gray-300 focus:border-indigo-500 focus:ring-indigo-500': !hasError }
        )}
      >
        {options.map(({ text, value }) => (
          <option key={value} value={value}>
            {text}
          </option>
        ))}
      </select>
      {hasError && (
        <div data-testid={`${field.name}-field-error`} className='mt-1 px-2 text-sm text-red-400'>
          {error}
        </div>
      )}
    </div>
  );
}

export default FormSelect;
