// LIBRARIES
import React, {Component} from 'react';
import { Row, Col, Tooltip, Button, Modal, Select, Input } from 'antd';
import { Form, Field } from 'formik';
import { connect } from 'react-redux';
import HeaderForm from "components/Forms/HeaderForm"
import { API_UNI_OIL } from 'utils/StationApi';
import { compose, withProps, lifecycle } from "recompose"
import { DeleteFilled } from '@ant-design/icons';
import { GoogleMap, withScriptjs, withGoogleMap, Marker } from 'react-google-maps';
import { Inputs, InputTextArea, MultiSelectOptions, MultiSelect } from 'components/Forms';
import { all } from '../../../../../../node_modules/redux-saga/effects';


const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
};

const center = {
  lat: 16.1505,
  lng: 119.9856
};
const containerStyle = {
  width: 'inherit',
  height: '300px',
  marginBottom: '20px'
};
const text = 
  <Row className="flex-column" style={{ textAlign: 'center', }}>
    <Col>Accepted Numbers Format:</Col>
    <Col>+(63)9*********</Col>
    <Col>+639*********</Col>
    <Col>(02)****-****</Col>
    <Col>6***-****</Col>
  </Row>


const MyMapComponent = compose(
  withProps({
      googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyARzdIELzb2Uvoly4-Er4B7-QzXKr4j3bg&libraries=geometry,drawing,places",
      loadingElement: <div style={{ height: `100%` }} />,
      containerElement: <div style={{ height: `400px`, marginBottom: '30px'}} />,
      mapElement: <div style={{ height: `100%` }} />,
  }),
  lifecycle({
    componentWillMount() {
      const refs = {}
      this.setState({
        position: null,
        onMarkerMounted: ref => {
            refs.marker = ref;
        },
        onPositionChanged: () => {
          const position = refs.marker.getPosition();
          let urlMap =refs.marker.context.__SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.mapUrl
          let sample = position.toString()
          let lat = sample.split(',')[0].substring(1)
          let long = sample.split(',')[1].slice(1,-1)
          this.props.getData(urlMap, lat, long)
        }
      })
    },
  }),
  withScriptjs,
  withGoogleMap
  )
  ((props) =>
    <GoogleMap defaultZoom={15} center={props.center ? props.center : center}>
        {props.isMarkerShown && <Marker position={props.center ? props.center : center} draggable={true} ref={props.onMarkerMounted} onPositionChanged={props.onPositionChanged} />}
    </GoogleMap>
  )

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

class FormLocation extends Component {
  state = {
    value: [],
    map: null,
    selectData: [],
    fuelsData: [],
    fuels:[],
    newData: [],
    isSched: false,
    fuelsToUpdate: [],
    addFuelModal: false,
    newFuel: [],
    removeModal: false,
    fuelName: '',
    fuelIndex: '',
  };

  ref; 
  
  // onChange = (e) => {
  //   this.setState({value: e})
  // }

  handleSubmit = async (values, actions) => {
  }

  // handleChange = (data) => {
  //   const obj = [];
  //   const result = this.state.fuelsData.filter(({id}) => data.includes(id));
  //   this.setState({value: result})
  // }

  getUrl = (url, lat, long) => {
    this.props.mapData(url, lat, long)
  }

  componentDidMount(){
    this.getBranches()
    this.getFuels()
  }

  getBranches = async() => {
    try {
      const response = await API_UNI_OIL.get('branches/noLimit', '');
      if(response) {
        this.setState({ loading: false, selectData: response.data.data });
      }
    } catch (error) {
      this.setState({ loading: false });
    }
  }

  getFuels = async() => {
    try {
      const response = await API_UNI_OIL.get('fuels', '');
      if(response) {
        this.setState({ loading: false, fuelsData: response.data.data, fuels: response.data.data  });
      }
    } catch (error) {
      console.log(error)
      this.setState({ loading: false });
    }
  }

  handleChangeFuels = (e, id) => {
    const newState = this.state.newFuel.map(obj =>
      obj.id === id ? { ...obj, price: e, FuelId: id } : obj
    );
    console.log("Fuel Changed", this.state.newFuel)
    this.setState({value: newState, newFuel: newState})
    this.props.fuelId(newState)
  }

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

  addToStationFuel = () => {
    let data = this.state.fuelsData
    let val = this.state.value
    let nf = this.state.newFuel
    let arr1 = val.filter(id => !nf.includes(id));
    let sa = nf.concat(arr1)
    let arr2 = data.filter(id => !val.includes(id))
    this.props.fuelId(sa)
    this.setState({fuelModal: false, newFuel: sa, fuelsData:arr2, 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.newFuel
    data.splice(this.state.fuelIndex, 1)
    console.log(data)
    this.setState({newFuel: data, removeModal: false})
  }

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

  handleAddFuelModal = () => {
    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.fuelsData = select; this.ref = select}}
            optionLabelProp="label"
            mode="multiple"
            onChange={(e)=> this.getAddedFuel(this.fuelsData,e)}
            open={this.state.selectMenu}
            onFocus={()=> this.setState({selectMenu:true})}
            defaultOpen={false}
          >
            {
              this.state.fuelsData.map((item,i) => {
                return <Option value={item.id} key={`${i}-${item.name}`} label={item.name}>{item.name}</Option>
              })
            }
          </Select>
      </Modal>
    )
  }



 render(){
    const { handleSubmit, history,dataToDisplay } = this.props
  return (
    <Form noValidate>
      <HeaderForm
        loading={this.state.loading}
        disabled={false}
        title={this.props.title}
        action={handleSubmit}
        actionBtnName="Save"
        withCancelConfirm={{ message: 'Are you sure you want to discard changes?'}}
        cancel={()=> { window.location.replace("/stations")}}
        cancelBtnName="Cancel"
      />
      <MyMapComponent isMarkerShown={true} center={dataToDisplay} getData={this.getUrl}/>
      <Field
        name="map_URL"
        type="text"
        icon=""
        layout={formItemLayout}
        label="Map URL"
        disabled={false}
        placeholder=""
        component={InputTextArea}
      />
      <Field
        name="lat"
        type="date-time"
        icon=""
        layout={formItemLayout}
        label="Latitude"
        placeholder=""
        disabled={false}
        component={Inputs}
      />
      <Field
        name="long"
        type="date-time"
        icon=""
        layout={formItemLayout}
        label="Longitude"
        disabled={false}
        placeholder=""
        component={Inputs}
      />
       <Field
        name="code"
        type="text"
        icon=""
        layout={formItemLayout}
        label="Station Code"
        placeholder="Station Code"
        component={Inputs}
      />
      <Field
        name="name"
        type="text"
        icon=""
        layout={formItemLayout}
        label="Station Name"
        placeholder="Station Name"
        component={Inputs}
      />
      <Field
        name="location"
        type="text"
        icon=""
        layout={formItemLayout}
        label="Station Location"
        placeholder="Complete Station Information"
        component={Inputs}
      />
      
      <Tooltip placement="bottom" title={text} color="red">
        <Field
          name="contact_number"
          type="text"
          icon=""
          layout={formItemLayout}
          label="Contact Number"
          placeholder="Contact Number"
          component={Inputs}
          style={{margin: '0px 0px 0px 0px !important'}}
        />
      </Tooltip>

  

      <Field
        name="BranchId"
        type="text"
        icon=""
        layout={formItemLayout}
        label="Branch"
        showSearch
        placeholder="Select Branch"
        optionFilterProp="children"
        placeholder="Select branch"
        optionsList={this.state.selectData}
        component={MultiSelect}
        filterOption={(input, option) => 
          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
      />
      {
        this.props.edit ? <div></div> : 
        <div>
          <Row>
            <Col style={{ float: 'right', margin: '5px', paddingRight: '5.7vw' }}>
              <Button 
                style={{ background: '#E74610', borderColor:'#E74610', color: '#fff',}}
                onClick={()=> this.handleShowFuelAdd()} 
              >
                Add fuel
              </Button>
            </Col>
          </Row>
          {
            this.state.newFuel.length == 0 ? '' :
              this.state.newFuel.map((val, index)=>{
              return(
                <Row style={{ margin: '5px' }}>
                  <Col span={4} style={{textAlign: 'right', paddingRight: '5px', paddingTop: '5px', fontWeight: 500}}>
                    <p>{val.name}</p>
                  </Col>
                  <Col span={18}>
                    <Input
                      addonAfter={<DeleteFilled onClick={()=> this.setState({fuelIndex:index, fuelName: val.name, removeModal: !this.state.removeModal})}/>}
                      type="number"
                      label={val.name}
                      value={val.id != 'null' || val.id != '' ? val.price == "0.00" ? "0" + val.price : val.price : 0}
                      placeholder='00.00'
                      onChange={(e)=> this.handleChangeFuels(e.target.value, val.id)}
                    />
                  </Col>
                </Row>
              )
            })
          }
        </div>
      }
      {this.handleAddFuelModal()}
      {this.handleShowConfirmationModal()}
    </Form>
  )};
};


FormLocation = connect(
  state => ({

  }),
)(FormLocation);


export default FormLocation;

