// LIBRARIES
import React, { Component } from 'react';
import { Menu, Dropdown, Row, Col, Modal, Radio,DatePicker, notification, Button, Select, Input } from "antd"
import { Formik , Field} from 'formik'
import { connect } from "react-redux"
import { customAction } from "actions";
import { locationDetailsSchema } from '../validationSchema'
import AddUserManagementForm from '../components/stationForm'
import {API_UNI_OIL, API_PUT_BRANCH} from 'utils/StationApi'
import moment from 'moment'
import { DeleteFilled } from '@ant-design/icons';
import * as Yup from 'yup'
import { secretbox } from '../../../../../../node_modules/tweetnacl/nacl';

const styles = {
  ':select': {
    backgroundColor: 'yellow',
    color: 'red'
  }
};

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
};
  class EditStation extends Component {
    state= {
      updating: false,
      isGenerated: false,
      loading: false,
      latitude: '',
      longitude: '',
      urlMap: '',
      name: '',
      location: '',
      contactNum: '',
      branchId: '',
      fuels: [],
      isSched: 2,
      date: null,
      latLong: {},
      fuelModal: false,
      newFuel: [],
      fuelsData: [],
      value: [],
      removeModal: false,
      fuelName: '',
      fuelIndex: '',
      stationCode: '',
      selectMenu: false,
    }

    ref;

    async componentDidMount(){
    
    const { match } = this.props;

    try {
      let response = await API_UNI_OIL.get(`stations/${match.params.id}`)
      console.log('Data Fetched',response.data)
      let data = {lat: parseFloat(response.data.lat), lng: parseFloat(response.data.long)}
      this.setState({
        name: response.data.name,
        location: response.data.location,
        contactNum: response.data.contact_number,
        branchId: response.data.BranchId,
        urlMap: response.data.map_Url,
        latitude: response.data.lat,
        longitude: response.data.long,
        fuels: this.sortFuels(response.data.StationFuels),
        mounted: true,
        latLong: data,
        date: response.data.Schedule,
        stationCode: response.data.code,
        isSched: response.data.Schedule == null ? 2 : 1
      })
      } catch ({response: error}) {
        notification.error({
          message: "Error",
          description: <div>
            <div>Something went wrong loading data.</div>
          - { error && error.data && error.data.message }
          </div> ,
          duration: 3,
        });
        if(error.status == 404) {
          if(this.props.location.pathname)
            this.props.history.push(`${this.props.location.pathname}/404`); return
        }
        this.setState({ mounted: false })
      }
      this.getFuels()
    }

    getFuels = async() => {
      try {
        const response = await API_UNI_OIL.get('fuels', '');
        if(response) {
          this.setState({ newFuel: response.data.data, fuelsData: response.data.data });
          let data = this.state.fuels
          data.map(fuel => {
            let newArray = this.state.newFuel.filter(function(element) {
              return element.id !== fuel.FuelId;
            });
            
            let allFuels = newArray.sort((a, b) => {
              if (a.name < b.name)
                return -1;
              if (a.name > b.name)
                return 1;
              return 0;
            })


            this.setState({newFuel: allFuels})
          })
        }
      } catch (error) {
        console.log(error)
      }
    }


    handleSubmit = async (data, actions) => {
      const { setErrors, setSubmitting } = actions;
      let { history, match } = this.props;
      let _self = this;
      const result = this.state.fuels.map(({ FuelId, price }) => ({FuelId: FuelId, price}));
      let id = match.params.id
      let user = localStorage.getItem('user')
      let values = {
        'name': data.name,
        'location': data.location,
        'map_Url': data.map_URL,
        'lat': data.lat,
        'long':data.long,
        'contact_number': data.contact_number.toString(),
        'modified_by': user,
        'BranchId': data.BranchId.toString(),
        'Schedule': this.state.isSched === 1 ? this.state.date : this.state.isSched === 0 ? null : null,
        'NewStationFuel': result,
        'code': data.code.toString()
      }
      let inv = false;
      this.state.fuels.map((value) => {
        if(value.price == 0 || value.price == 0.00 || value.price == "0.00" || value.price == "00.00" || value.id == undefined){          
          inv = true
        }
      })
      if(inv){
        notification.error({
          message: "Error",
          description: <div>
            <div>Invalid Price for Fuel.</div>
          </div> ,
          duration: 3,
        });
        return
      }
      if(this.state.fuels == 0 && this.state.isSched == 1){
        notification.error({
          message: "Error",
          description: <div>
            <div>Can't schedule a station without Fuel.</div>
          </div> ,
          duration: 3,
        });
        return;
      }
      if(this.state.isSched == 2) {
        notification.error({
          message: "Error",
          description: <div>
            <div>Please select a schedule update value.</div>
          </div> ,
          duration: 3,
        });
      }
      else {
        this.props.customAction({
          type: "STATION_UPDATE_REQUEST",
          payload: {
            id,
            values,
            setSubmitting,
            setErrors,
            history,
            _self
          }
        });
      }
      console.log('Data Submitted', values)
    }

   getMapdata = (url, lat, long) => {
    this.setState({urlMap: url, latitude: lat, longitude: long})
    }

    updateFuels = (e, id, bool) => {
      if(bool){
        const newState = this.state.fuels.map(obj =>
          obj.FuelId === id ? { ...obj, price: e, FuelId: id } : obj
        );
      this.setState({fuels: newState})
      }else{
        const newState = this.state.fuels.map(obj =>
          obj.id === id ? { ...obj, price: e, FuelId: id } : obj
        );
      this.setState({fuels: newState})
      }
    }

    handleChangeRadio = (e) => {
      this.setState({isSched: e.target.value})
    }

    onDateChange = (date, dateString) => {
      console.log('date', dateString)
      this.setState({date: dateString})
    }

    getAddedFuel = (select, data) => {
      console.log(select, data)
      const obj = [];
      const result = this.state.fuelsData.filter(({id}) => data.includes(id),{...obj, FuelId: data});
      this.setState({value: result, selectMenu: false});
      select.blur()
    }

    addToStationFuel = () => {
      let data = this.state.fuels
      let val = this.state.value
      let nf = this.state.newFuel
      let arr1 = val.filter(id => !data.includes(id));
      let sa = data.concat(arr1)
      let arr2 = nf.filter(id => !val.includes(id))
      this.setState({fuelModal: false, fuels: sa, newFuel:arr2, selectMenu:false, })
    }

    handleFuelModal = () => {
    const Option = Select.Option;
      return(
        <Modal id='locationAddModal'
           title="Add Fuel"
           visible={this.state.fuelModal}
           closable={false}
           footer={[
            <Button style={{
              background: '#E74610', borderColor:'#E74610',
              color: '#fff'
            }} onClick={()=> {
              this.addToStationFuel()
              this.ref.rcSelect.fireChange([])
            }}>
              Add fuel
            </Button>,
             <Button key="back" onClick={()=> this.handleShowFuelAdd()}>
               Close
             </Button>
           ]}
          >
           <Select
            style={{ width: '100%' }}
            placeholder="Select fuels."
            defaultValue={[]}
            ref={(select) => {this.fuels = select; this.ref = select}}
            optionLabelProp="label"
            mode="multiple"
            onChange={(e)=> this.getAddedFuel(this.fuels,e)}
            open={this.state.selectMenu}
            onFocus={()=> this.setState({selectMenu:true})}
            defaultOpen={false}
          >
            {
              this.state.newFuel.map((item,i) => {
                return <Option value={item.id} key={`${i}-${item.name}`} label={item.name}>{item.name}</Option>
              })
            }
          </Select>
        </Modal>
      )
    }

    handleShowFuelAdd = () => {
      this.setState({fuelModal: !this.state.fuelModal, selectMenu:false})
    }

    handleShowConfirmationModal = () => {
      return(
        <Modal id='removeModal'
           title="Remove Fuel"
           visible={this.state.removeModal}
           closable={false}
           footer={[
            <Button style={{
              background: '#E74610', borderColor:'#E74610',
              color: '#fff'
            }} onClick={()=> this.removeFuel()}>
              Remove
            </Button>,
             <Button key="back" onClick={()=> this.setState({removeModal: false})}>
               Close
             </Button>
           ]}
          >
           <p>Are you sure you want to remove {this.state.fuelName} ?</p>
        </Modal>
      )
    }

    removeFuel = () => {
      let data = this.state.fuels
      data.splice(this.state.fuelIndex, 1)
      console.log(data)
      this.setState({fuels: data, removeModal: false})
    }

    disabledDate(current) {
      // Can not select days before today and today
      return current && current < moment().startOf('day');
    }

    onOk(value) {
      console.log('onOk: ', value);
    }

    sortFuels(data){
      let tosort = [];
      for(var x=0;x<data.length;x++){
        let s = data[x].Fuel.name.split(" ")
        let ts = Number(s[s.length -1]) || 0
        tosort.push({val: ts, data: data[x]})
      }
      let ttss = tosort.sort((a, b) => {
        return a.val - b.val
      })
      let fts = ttss.map((item, i) => {
        return item.data
      })
      return fts
    }

    render() {
      const { match, history } = this.props;
      let { isGenerated,loading } = this.state;
   
      return (
        <div style={{marginBottom: '20px'}}>
          <Formik
            initialValues={{
              name: this.state.name,
              location: this.state.location,
              map_URL: this.state.urlMap,
              lat: this.state.latitude,
              long: this.state.longitude,
              contact_number: this.state.contactNum,
              BranchId: this.state.branchId,
              code: this.state.stationCode
            }}
            ref={node => (this.form = node)}
            enableReinitialize={true}
            validationSchema={locationDetailsSchema}
            onSubmit={this.handleSubmit }
            render = {(props)=>
              <AddUserManagementForm
                {...props}
                title='Edit Station'
                mapData={this.getMapdata}
                history={this.props.history}
                dataToDisplay={this.state.latLong}
                isGenerated={isGenerated}
                fuels={this.state.fuels}
                edit={true}
              />
            }
          />
          {
            <Row style={{margin: '15px 0 5px 0'}}>
              <Col span={4}>
                <p style={{textAlign: 'right', paddingRight: '8px'}}>Scheduled Update:</p>
              </Col>
              <Col span={4}>
                <Radio.Group defaultValue={this.state.isSched} value={this.state.isSched} onChange={(e)=> this.handleChangeRadio(e)}>
                  <Radio value={0} key='false' style={styles}>No</Radio>
                  <Radio value={1} key='true' style={styles}>Yes</Radio>
                </Radio.Group>
              </Col>
              <Col span={11}>
              {
                this.state.isSched == true ?
                  <Row>
                    <Col span={8}>
                      <p>Scheduled Date and Time:</p>
                    </Col>
                    <Col style={{marginTop: '-5px'}}>
                      <DatePicker
                        onChange={this.onDateChange}
                        value={ this.state.date == '' || this.state.date == null ? "" : moment(this.state.date)}
                        onOk={this.onOk}
                        showTime={{ format: 'HH:mm' }}
                        format='YYYY-MM-DD HH:mm'
                        disabledDate={this.disabledDate}
                        style={{width: '250px', marginRight: '15px'}}
                      />
                    </Col>
                  </Row>
                  :
                  ''
              }
              </Col>
              <Col span={3}>
                <Button style={{
                    display: 'block', background: '#E74610', borderColor:'#E74610',
                    color: '#fff'
                  }} block onClick={()=> {
                    this.handleShowFuelAdd()
                  }}>Add fuel</Button>
              </Col>
            </Row>
          }
          {
              this.state.fuels.map((item,index)=>{
                let name = item.Fuel ? item.Fuel.name : item.name
              return (
                <Row>
                <Col span={4} style={{textAlign: 'right', paddingRight: '5px', paddingTop: '5px', fontWeight: 500}}>
                  <p>{name}</p>
                </Col>
                <Col span={18}>
                  <Input
                    addonAfter={<DeleteFilled onClick={()=> this.setState({fuelIndex:index, fuelName: name, removeModal: !this.state.removeModal})}/>}
                    type="number"
                    value={item.FuelId != 'null' || item.FuelId != '' ? item.price == "0.00" ? "0" + item.price : item.price : 0}
                    label={name}
                    placeholder={name}
                    onChange={(e)=> this.updateFuels(e.target.value, item.Fuel ? item.FuelId : item.id, item.Fuel ? true : false)}
                  />
                </Col>
              </Row>
              )
            })
            }
            {this.handleFuelModal()}
            {this.handleShowConfirmationModal()}
        </div>
      );
    }
  }

  EditStation = connect(
    state => ({
      //userInfo: state
      stationUpdate: state.stationUpdate,
    }),
    { customAction }
  )(EditStation);

  export default EditStation;