import React, {Component} from 'react'
import Spinner from 'react-spinjs'
import {MdInsertDriveFile} from 'react-icons/lib/md'
import styled from 'styled-components'
import Field from 'components/field'
import {color, link} from 'common/styles'
import auto_bind from 'common/auto_bind'

export default class TemplateField extends Component {
  constructor(props) {
    super(props)
    this.state = {
      templating: false,
    }
    auto_bind(this)
  }

  static defaultProps = {
    show_label: true,
    view_template() {},
  }

  view_template() {
    this.setState({templating: true})
    this.props.view_template()
    .then(() => this.setState({templating: false}))
  }

  render() {
    const {templating} = this.state
    return (
      <Field {...this.props} category="template">
        {templating ? (
          <Loading>
            <Spinner config={{length: 4, width: 2, radius: 5}} />
          </Loading>
        ) : (
          <Icon onClick={this.view_template}>
            <MdInsertDriveFile />
          </Icon>
        )}
      </Field>
    )
  }
}

const Icon = styled.div`
  padding-left: 5px;
  font-size: 24px;
  color: ${color('black', 'normal', 0.7)};
  ${link}

  &:hover {
    opacity: 1;
    color: ${color('primary')};
  }
`
const Loading = styled.div`
  width: 20px;
  height: 20px;
  position: relative;
  margin-left: 10px;
  margin-top: 5px;
`
