import React, { FormEvent } from 'react';
import { IconButton } from '../button/IconButton';
import styles from './caloriesInput.css';

type CaloriesInputProps = {
  addCalories: (calories: { title: string, count: number}) => void,
  saveCalories: (calories: { title: string, count: number}) => void,
  item?: CalorieValue
};

interface ICalorieInputForm extends HTMLFormElement {
  caloriesTitle: HTMLInputElement;
  caloriesCount: HTMLInputElement;
}

function CaloriesInput ({ addCalories, saveCalories, item }: CaloriesInputProps) {
  function onSubmit (event: FormEvent<ICalorieInputForm>) {
    event.preventDefault();

    const form = event.currentTarget;
    const title = form.caloriesTitle.value;
    const count = Number(form.caloriesCount.value) || 0;

    if (!item) {
      addCalories({ title, count });

      form.querySelectorAll('input').forEach((formElement) => {
        formElement.value = '';
        formElement.blur();
      });
    } else {
      saveCalories({ title, count});
    }
  }

  const {
    title: itemTitle = '',
    count: itemCount = ''
  } = item || {};

  const buttonIcon = item
    ? 'tick'
    : 'plus';

  return (
    <form onSubmit={onSubmit} className={styles.caloriesInput}>
      <div className={styles.inputWrapper}>
        <div className={styles.formRow}>
          <label htmlFor="caloriesTitle">Nahrungsmittel:</label>
          <input id="caloriesTitle" name="caloriesTitle" type="text" defaultValue={itemTitle} required />
        </div>

        <div className={styles.formRow}>
          <label htmlFor="caloriesCount">Kalorien:</label>
          <input id="caloriesCount" name="caloriesCount" type="number" defaultValue={itemCount} required />
        </div>
      </div>

      <div className={styles.buttonWrapper}>
        <IconButton icon={buttonIcon} buttonClassName={styles.addButton} />
      </div>
    </form>
  );
}

export {
  CaloriesInput
};
