import React, { useState, useEffect } from "react";
import { connect } from "react-redux";
import { Button, Header, Message } from "semantic-ui-react";
import ItemInputFormSearch from "./ItemInputFormSearch";
import { Form, Input, Select } from "formsy-semantic-ui-react";
import { postTracking } from "../actions";
import { getSearch } from "../reducers";
import { cleanQuery } from "../search-actions"

function ItemInputForm({search, refreshItems, selectedDate, postTracking, cleanQuery}) {
  const [unit, setUnit] = useState("g/ml");
  const [foodItem, setFoodItem] = useState<{_id: string} | undefined>(undefined);
  const [error, setError] = useState<string | undefined>(undefined);


  let itemForm;
  
  const mealOptions = [
    { value: "zmorge", text: "Morgenessen" },
    { value: "znueni", text: "Z'Nüni" },
    { value: "zmittag", text: "Mittagessen" },
    { value: "zvieri", text: "Z'Vierei" },
    { value: "znacht", text: "Nachtessen" },
  ];

  useEffect(() => {
  }, [search])

  const handleSearchValueChange = (value) => {
    setFoodItem(value);
    setUnit(value.bezugseinheit);
  };


  const onValidSubmit = (formData) => {

    if (foodItem) {
      formData.fooditem = foodItem?._id;
      formData.date = selectedDate;

      postTracking(formData).then(res => {
        itemForm.reset();
        cleanQuery();
        refreshItems();
        setError(undefined);
        setFoodItem(undefined);
        setUnit("g/ml");

      }).catch(() => {
        setError("Unbekannter Fehler!")
      })
    } else {
      setError("Gültiges Fooditem wählen!")
    }

  };


  return (
    <>
      <Header as="h3" content="Hinzufügen" />
      <Form onValidSubmit={onValidSubmit}
      ref={(event) => { itemForm = event; }}>
        <ItemInputFormSearch
          onChange={handleSearchValueChange} 
        ></ItemInputFormSearch>
        <Input
          name="amount"
          required
          className="ItemInputFormInput"
          label={{ basic: true, content: unit }}
          labelPosition="right"
          placeholder="Menge eingeben..."
        />
        <Select
          required
          name="mealOption"
          placeholder="Mahlzeit wählen..."
          options={mealOptions}
        />
        <Button
          color="brown"
          style={{ width: "100%" }}
        >
          Speichern
        </Button>
        {error && <Message color="red" content={error} />}

      </Form>
    </>
  );
}


const mapStateToProps = (state) => {
  return {
    search: getSearch(state)
  }
}

const mapDispatchToProps = {
  postTracking,
  cleanQuery
};

export default connect(mapStateToProps, mapDispatchToProps)(ItemInputForm);


