import React, {Component} from 'react'
import styled from 'styled-components'
import Button from 'components/utils/button'
import TimePickers, {
  day_id, get_days_chunks, get_periods, get_start_end,
} from 'components/input_calendar/time_pickers'
import auto_bind from 'common/auto_bind'
import moment from 'common/moment'
import store from 'common/store'
import {create_hash} from 'common/utilities'
import {color} from 'common/styles'
import {dismiss_popover} from 'actions/display'

export default class SlotPicker extends Component {
  constructor(props) {
    super(props)
    this.start = moment(props.slot.start).startOf('day')
    this.state = {
      chunks: get_days_chunks(props.slot.events || [props.slot])[day_id(this.start)] || {}
    }
    auto_bind(this)
  }

  flip(_, new_chunks, paint) {
    this.setState(({chunks}) => ({
      chunks: {
        ...chunks,
        ...create_hash(new_chunks, () => paint),
      },
    }))
  }

  submit() {
    const events = []
    get_periods(this.state.chunks).forEach(({start, end}) => {
      events.push({
        ...get_start_end(this.start, start, end),
        full_days: false,
      })
    })
    this.props.update_events(events)
    store.dispatch(dismiss_popover())
  }

  render() {
    return (
      <Container>
        <TimePickers
          day_label={false}
          days={[{date: this.start, chunks: this.state.chunks}]}
          flip={this.flip}
          drag_color={color('primary')}
          />
        <Button onClick={this.submit}>
          Enregistrer
        </Button>
      </Container>
    )
  }
}

const Container = styled.div`
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-left: -120px;
  padding-right: 20px;
  margin-top: 20px;
`
