import React from 'react'
import ModalDialog from './ModalDialog.jsx'

import client from '../client'

export default class MealView extends React.Component {
  constructor(props) {
    super()
    this.state = {
      user: Object.assign({}, props.user),
      meals: [],
    }
    this.updateUser = this.updateUser.bind(this)
  }
  updateUser(user) {
    this.setState({
      user: user
    })
  }
  render() {
    const user = this.state.user
    const meals = this.state.meals
    return (
      <div>
        <Menu user={user} currentUser={this.props.user} updateUser={this.updateUser} />
        <MealList user={user} currentUser={this.props.user} />
        <div className='users'>
          <UserList />
        </div>
      </div>
    )
  }
}

class Menu extends React.Component {
  constructor() {
    super()
    this.setGoal = this.setGoal.bind(this)
    this.logout = this.logout.bind(this)
  }
  setGoal() {
    const goal = Math.abs(parseInt(prompt('Please enter your calorie goal', this.props.user.goal)))
    if (goal) {
      client.service('users').patch(this.props.user.id, {
        goal: goal,
        token: client.get('token'),
      }).then((user) => {
        this.props.updateUser(user)
      })
    }
  }
  logout() {
    client.logout().then(() => {
      window.location.reload()
    })
  }
  render() {
    const user = this.props.user
    const items = []
    items.push( <li key='hello'>Hello {user.email}</li> )
    items.push( <li key='goal'><a href='#' onClick={this.setGoal}>Goal</a>: {user.goal}</li> )
    items.push( <li key='logout'><a href='#' onClick={this.logout}>Logout</a></li> )

    return (
      <div>
        <ul className='menu'>
          {items}
        </ul>
        <ProfileModal user={user} visible={false} onClose={() => {}} />
      </div>
    )
  }
}

class ProfileModal extends React.Component {
  render() {
    return (
      <ModalDialog visible={this.props.visible} onClose={this.props.onClose}>
      </ModalDialog>
    )
  }
}

class MealList extends React.Component {
  constructor(props) {
    super()

    this.state = {
      total: 0,
      limit: 0,
      skip: 0,
      data: []
    }

    this.handleCreate = this.handleCreate.bind(this)
    this.handleUpdate = this.handleUpdate.bind(this)
    this.handleDelete = this.handleDelete.bind(this)
    this.pickMeal = this.pickMeal.bind(this)

    client.service('meals').find({
      query: {
        userid: props.user.id,
        '$sort': { 'date': '-1' },
        token: client.get('token'),
      },
    }).then((data) => {
      this.setState(data)
    }).catch((error) => {
      console.error(error)
    })
  }
  handleCreate(meal) {
    const meals = this.state.data.slice()
    meals.unshift( meal )
    this.setState({
      data: meals.sort(sortByDate)
    })
  }
  handleUpdate(meal) {
    const meals = this.state.data.map((data, i) => {
      return (data.id === meal.id) ? meal : data
    }).sort(sortByDate)
    this.setState({
      data: meals
    })
  }
  handleDelete(mealid) {
    const meals = this.state.data.filter((data, i) => {
      return data.id !== mealid
    }).sort(sortByDate)
    this.setState({
      data: meals
    })
  }
  pickMeal(meal) {
    this.mealForm.pick(meal)
  }
  render() {
    const items = this.state.data.map((meal, i) => {
      return (
        <MealItem key={meal.id}
          meal={meal}
          onClick={this.pickMeal}
          onDelete={this.handleDelete} />
      )
    })
    return (
      <div>
        <MealForm user={this.props.user}
          ref={(mealForm) => { this.mealForm = mealForm }}
          onCreate={(meal) => { this.handleCreate(meal) }}
          onUpdate={(meal) => { this.handleUpdate(meal) }}
        />
        <div>
          {items}
        </div>
      </div>
    )
  }
}

class MealItem extends React.Component {
  constructor() {
    super()
    this.remove = this.remove.bind(this)
  }
  remove(e) {
    e.stopPropagation()
    const mealid = this.props.meal.id
    const mealsService = client.service('meals')
    const params = { query: { token: client.get('token') } }
    mealsService.remove(mealid, params).then(result => {
      this.props.onDelete(mealid)
    }).catch(error => {
      console.error(error)
    })
  }
  render() {
    const meal = this.props.meal
    // const canEdit = this.props.meal.userid === this.props.currentUser.id ? 'canEdit' : ''
    const canEdit = 'canEdit'
    const date = parseDate(meal.date)
    const time = parseTime(meal.time)
    return (
      <div className={'meal ' + canEdit} onClick={() => this.props.onClick(meal)}>
        <div className='name'>{meal.name}</div>
        <div className='calories'>{meal.calories} cal</div>
        <div className='date'>{date}</div>
        <div className='time'>{time}</div>
        <div className='remove' onClick={this.remove}>x</div>
      </div>
    )
  }
}

class MealForm extends React.Component {
  constructor(props) {
    super()
    this.state = {
      id: '',
      userid: props.user.id,
      name: '',
      calories: '',
      date: new Date (),
      time: new Date (),
    }
    this.updateState = this.updateState.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }
  reset() {
    this.setState({
      id: '',
      name: '',
      calories: '',
      date: new Date (),
      time: new Date (),
    })
  }
  pick(meal){
    this.setState(meal)
  }
  updateState(event){
    const name = event.target.name
    let value = event.target.value
    if (name === 'date') {
      value = new Date(value).toString()
    } else if (name === 'time') {
      value = new Date('1970-01-01T' + value).toString()
    } else if (name === 'calories') {
      value = parseInt(value)
    }
    this.setState({
      [name]: value,
      error: null,
    })
  }
  handleSubmit(event) {
    event.preventDefault()

    const id = this.state.id

    if (! id) {
      this.create()
    }
    else {
      this.update()
    }
  }
  create() {
    const mealsService = client.service('meals')
    const params = { query: { token: client.get('token') } }
    mealsService.create(this.state, params).then(result => {
      this.props.onCreate(result)
      this.reset()
    }).catch(error => {
      console.error(error)
      this.setState({
        error: error.toString()
      })
    })
  }
  update() {
    const mealsService = client.service('meals')
    const params = { query: { token: client.get('token') } }

    mealsService.update(this.state.id, this.state, params).then(result => {
      this.props.onUpdate(result)
      this.reset()
    }).catch(error => {
      console.error(error)
      this.setState({
        error: error.toString()
      })
    })
  }
  render() {
    const id = this.state.id
    const action = id ? 'update' : 'create'

    const date = parseDate(this.state.date)
    const time = parseTime(this.state.time)
    return (
      <form onSubmit={this.handleSubmit} className={action}>
        <input type='hidden' name='id' value={this.state.id} readOnly />
        <input type='hidden' name='userid' value={this.state.userid} readOnly />
        <input type='text' name='name' placeholder='Name' value={this.state.name} required onChange={this.updateState} />
        <input type='number' name='calories' placeholder='Calories' value={this.state.calories} required onChange={this.updateState} min='0' max='10000' />
        <input type='date' name='date' placeholder='Date' value={date} required onChange={this.updateState} />
        <input type='time' name='time' placeholder='Time' value={time} required onChange={this.updateState} step='60' />
        <input type='submit' value={capitalize(action)} />
        <span className='clear' onClick={() => this.reset()}>clear</span>
        <div className='error'>{this.state.error}</div>
      </form>
    )
  }
}

function sortByDate(a,b){
  return new Date(b.date) - new Date(a.date)
}

function parseDate(d){
  return new Date(d).toISOString().substr(0, 10)
}

function parseTime(d){
  return new Date(d).toISOString().substr(11, 5)
}

function capitalize(s){
  s = s || '';
  return (s[0] || '').toUpperCase() + s.substr(1)
}

class UserList extends React.Component {
  render() {
    const items = []
    return (
      <div>
        {items}
      </div>
    )
  }
}
