import { IonInput, IonLabel } from '@ionic/react';
import styles from './style.module.scss';

interface CustomFieldProps {
  field: {
    id: string;
    label: string;
    required: boolean;
    input: {
      props: {
        type:
          | 'date'
          | 'email'
          | 'number'
          | 'password'
          | 'search'
          | 'tel'
          | 'text'
          | 'url'
          | 'time'
          | 'week'
          | 'month'
          | 'datetime-local';
        placeholder: string;
        //
      };
      state: {
        value: string;
        reset: (newValue: any) => void;
        onIonChange: (e: any) => Promise<void>;
        onKeyUp: (e: any) => Promise<void>;
      };
    };
  };
  errors: any;
}

function CustomField({ field, errors }: CustomFieldProps): React.JSX.Element {
  const error = errors && errors.filter((e: { id: string }) => e.id === field.id)[0];
  const errorMessage = error && errors.filter((e: { id: string }) => e.id === field.id)[0].message;

  return (
    <>
      <div className={styles.field}>
        <IonLabel className={styles.fieldLabel}>
          {field.label}
          {error && <p className="animate__animated animate__bounceIn">{errorMessage}</p>}
        </IonLabel>
        <IonInput
          className={styles.customInput}
          {...field.input.state}
          {...field.input.props}
          //
        />
      </div>
    </>
  );
}

export { CustomField };
