import React, { useState, useEffect, useCallback } from "react";
import {
  Grid,
  Header,
  Segment,
  Image,
} from "semantic-ui-react";
import { signout, getTrackingByDate } from "../actions";
import { connect } from "react-redux";
import { getUser } from "../reducers";
import FoodAccordion from "../components/FoodAccordion";
import ItemInputForm from "../components/ItemInputForm";
import DateControlSegment from "../components/DateControlSegment";



function Home({ getTrackingByDate, user, refreshToken }) {
  const initialDate = new Date();
  initialDate.setUTCHours(0, 0, 0, 0);

  const [selectedDate, setSelectedDate] = useState<Date>(initialDate);
  const [accordionLoading, setAccordionLoading] = useState(false);
  const [meals, setMeals] = useState([])


  const refreshItems = useCallback(
    () => {
      setAccordionLoading(true);

    getTrackingByDate(selectedDate)
      .then((res) => {
        setMeals(res);
      })
      .finally(() => setAccordionLoading(false));
    },
    [getTrackingByDate, selectedDate],
  )

  useEffect(() => {
    refreshItems();

  }, [refreshItems]);



  return (
    <Grid className="HomeGrid" verticalAlign="middle" centered>
      <Grid.Column textAlign="center">
        <Image src="/images/breakfast.svg" size="small" centered />
        <Header as="h1">
          Hallo {user.username}
        </Header>

        <Segment.Group className="HomeSegement">
          <DateControlSegment
            selectedDate={selectedDate}
            setSelectedDate={setSelectedDate}
          ></DateControlSegment>
          <Segment>
            <Grid textAlign="left" divided columns={2}>
              <Grid.Column width={10}>
                <FoodAccordion refreshItems={refreshItems} isLoading={accordionLoading} meals={meals} />
              </Grid.Column>
              <Grid.Column width={6}>
                <ItemInputForm refreshItems={refreshItems} selectedDate={selectedDate}></ItemInputForm>
              </Grid.Column>
            </Grid>
          </Segment>
        </Segment.Group>
      </Grid.Column>
    </Grid>
  );
}

const mapStateToProps = (state) => {
  return {
    user: getUser(state),
  };
};

const mapDispatchToProps = {
  signout,
  getTrackingByDate,
};

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