import React, { Component, Fragment } from 'react';
import { inject, observer } from "mobx-react";
import { WingBlank, WhiteSpace, List, Stepper, Picker, Calendar, InputItem, TextareaItem, Radio, Toast, Button } from 'antd-mobile';
import SecondaryLayout from '@/layouts/SecondaryLayout';
import * as Icons from '@/components/Icons';

const calendar_enUS = {
    "am": "AM",
    "begin": "Start",
    "begin_over": "S/E",
    "clear": "Clear",
    "confirm": "Confirm",
    "dateFormat": "yyyy/MM/dd w",
    "dateTimeFormat": "MM/dd/yyyy w hh:mm",
    "end": "End",
    "lastMonth": "Last Month",
    "lastWeek": "Last Week",
    "loadPrevMonth": "Load Prev Month",
    "month": "Month",
    "monthTitle": "yyyy/MM",
    "noChoose": "No Choose",
    "over": "End",
    "pm": "PM",
    "selectEndTime": "Select End Time",
    "selectStartTime": "Select Start Time",
    "selectTime": "Select Time",
    "start": "Start",
    "title": "Select Departute Date",
    "today": "Today",
    "week": ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
    "year": "Year",
    "yesterday": "Yesterday"
};

@inject("store")
@observer
export class BookingView extends Component {
    originbodyScrollY = document.getElementsByTagName('body')[0].style.overflowY;
    constructor(props) {
        super(props);
        this.store = this.props.store;
        this.cityStore = this.store.cityStore;
        this.bookStore = this.store.bookStore;
        /** todo:delete */
        // this.cityStore.getTour(this.props.match.params.city, this.props.match.params.tourId);
        this.state = {
            show: false,
        };

        this.minDate = new Date();
        this.minDate.setDate(this.minDate.getDate() + this.cityStore.tourObj.activity.bookingCutoffDays);
        this.openWeekday = [];
        this.offWeekday = [];
        if (this.cityStore.tourObj.activity.hasOpeningHours === true) {
            let openSetting = this.cityStore.tourObj.activity.seasonalOpeningHours.length !== 0 ? this.cityStore.tourObj.activity.seasonalOpeningHours[0] : this.cityStore.tourObj.activity.defaultOpeningHours;
            openSetting.monday.timeIntervals.length === 0 ? this.offWeekday.push(1) : this.openWeekday.push(1);
            openSetting.tuesday.timeIntervals.length === 0 ? this.offWeekday.push(2) : this.openWeekday.push(2);
            openSetting.wednesday.timeIntervals.length === 0 ? this.offWeekday.push(3) : this.openWeekday.push(3);
            openSetting.thursday.timeIntervals.length === 0 ? this.offWeekday.push(4) : this.openWeekday.push(4);
            openSetting.friday.timeIntervals.length === 0 ? this.offWeekday.push(5) : this.openWeekday.push(5);
            openSetting.saturday.timeIntervals.length === 0 ? this.offWeekday.push(6) : this.openWeekday.push(6);
            openSetting.sunday.timeIntervals.length === 0 ? this.offWeekday.push(0) : this.openWeekday.push(0);
        }
        if (this.offWeekday.includes(this.minDate.getDay())) {
            for (const o of this.openWeekday) {
                if (o > this.minDate.getDay() && this.minDate.getDay() !== 0) {
                    this.minDate.setDate(this.minDate.getDate() + (o - this.minDate.getDay()));
                    break;
                } else {
                    let diff = this.minDate.getDate() - this.minDate.getDay() + o;
                    if (this.minDate.getDay() === 0) {
                    } else {
                        diff += 7;
                    }
                    this.minDate.setDate(diff);
                    break;
                }
            }
        }
    }
    componentDidMount() {
        this.bookStore.resetPaid();
        if (this.bookStore.startDate === null || this.bookStore.startDate === 'Invalid Date') {
            this.bookStore.setDate(this.minDate);
        }
        if (this.bookStore.fullname === '') {
            this.bookStore.fillFullname(this.bookStore.passengerList[0].fullname);
        }
        if ("" !== this.cityStore.tourObj.activity.title) {
            if (this.cityStore.tourObj.activity.startPoints.length === 0) {
                this.bookStore.setPickup('custom', 'I will write down the address')
            }
            // rate init
            const change_tour = this.cityStore.tourObj.activity.rates.find(
                ({ id }) => id === this.bookStore.rate.rateId
            )
            if (Object.keys(this.bookStore.rate).length === 0 || change_tour === undefined) {
                this.bookStore.setRate(this.cityStore.tourObj.activity.rates[0].id);
            }
        }
    }

    onChangeTravelers = (num, p) => {
        const amount = p.price ? p.price.amount : p.tieredPrices;
        this.bookStore.setTravelers(p.ticketCategory, num, amount);
    }
    onChangeAdults = (adult) => {
        this.bookStore.setAdultNum(adult);
    }
    onChangeChild = (child) => {
        this.bookStore.setChildNum(child);
    }
    onChangeDate = (date) => {
        this.bookStore.setDate(date);
    }
    onClickEnterTraveler = () => {
        this.store.pushHistory(this.props.location.pathname + '/travelers');
    }
    onClickSubmit = (e) => {
        Toast.loading('', 0);
        this.bookStore.calPrice()
            .then(r => {
                Toast.hide();
                this.store.pushHistory('/book/paynow');
            })
            .catch(e => {
                Toast.offline(e, 2)
            });
    }
    fillFullname = (value) => {
        this.bookStore.fillFullname(value);
    }
    fillEmail = (value) => {
        this.bookStore.fillEmail(value);
    }
    fillMobile = (value) => {
        this.bookStore.fillMobile(value);
    }
    fillRequests = (value) => {
        this.bookStore.fillRequests(value);
    }
    fillPickupAddress = (value) => {
        this.bookStore.fillPickupAddress(value);
    }
    fillHotelAddress = (value) => {
        this.bookStore.fillHotelAddress(value);
    }
    fillHotelName = (value) => {
        this.bookStore.fillHotelName(value);
    }
    fillCheckinName = (value) => {
        this.bookStore.fillCheckinName(value);
    }
    onErrorClick = (msg) => {
        Toast.info(msg, 2, null, false);
    }
    onCancelDate = () => {
        document.getElementsByTagName('body')[0].style.overflowY = this.originbodyScrollY;
        this.setState({
            show: false,
        });
    }
    onConfirmDate = (startTime, endTime) => {
        document.getElementsByTagName('body')[0].style.overflowY = this.originbodyScrollY;
        this.setState({
            show: false,
        });
        this.bookStore.setDate(startTime);
    }
    disableDate = (date) => {
        let weekday = date.getDay();
        if (this.cityStore.tourObj.activity.hasOpeningHours === true
            && (true === this.offWeekday.includes(weekday))
        ) {
            return { info: 'Closed', disable: true }
        }
    }
    onSelectPickup = (value) => {
        const label = value === 'custom' ? 'I will write down the address' : 'I don\'t need pick-up, I will meet you on location';
        this.bookStore.setPickup(value, label);
    }
    onSelectRate = (value) => {
        this.bookStore.setRate(value);
    }
    onClickCountry = () => {
        this.store.pushHistory('/book/select-country');
    }
    goBack = () => {
        this.store.goBack();
    }
    onFocus = (e) => {
        e.target.scrollIntoView({behavior: "smooth"});
    }

    render() {
        const tour = (this.cityStore.tourObj.activity);
        let tourRate = [];
        if (tour.rates === undefined) {
            return (
                <SecondaryLayout navTitle="Booking">
                    <WingBlank>
                        <h3>The data you entered has been lost since the page was refreshed.</h3>
                        <Button type="ghost"
                            onClick={this.goBack}
                        >&laquo; Back to tour page</Button>
                    </WingBlank>
                </SecondaryLayout>
            )
        }
        tour.rates.map(r => {
            // if (r.dropoffSelectionType==='PRESELECTED' || r.pickupSelectionType==='PRESELECTED') {
            return tourRate.push({ label: r.title, value: r.id });
            // }
        })
        let pickupOption = [{ label: 'I will write down the address', value: 'custom' }, { label: 'I don\'t need pick-up, I will meet you on location', value: 'meetingpoint' }];
        let pickupInfoText = 'Your pick-up information';
        if (tour.meetingType==='MEET_ON_LOCATION') {
            pickupInfoText = 'Select a starting point location where we could meet you on.'
        }
        return (
            <SecondaryLayout navTitle="Booking">
                <WingBlank>
                    <h4>{tour.title}</h4>
                </WingBlank>
                {tourRate.length > 1 &&
                    <List >
                        <Picker
                            dismissText="Cancel"
                            okText="OK"
                            title="Pricing Category"
                            extra={null}
                            cols={1}
                            data={tourRate}
                            onOk={e => this.onSelectRate(e[0])}
                            value={[this.bookStore.rate.rateId]}
                            error={true}
                        >
                            <div
                                style={{ backgroundColor: '#fff', paddingLeft: 15 }}
                            >
                                <div style={{ display: 'flex', height: '45px', lineHeight: '45px' }}>
                                    <div style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: '#007D9E', fontSize: '17px' }}>
                                        {this.bookStore.rate.title}
                                    </div>
                                    <div style={{ textAlign: 'right', padding: '5.5px 0 11.5px 0', color: '#888', marginRight: 15 }}>{Icons.DOWN}</div>
                                </div>
                            </div>
                        </Picker>
                    </List>
                }
                <WhiteSpace />
                {this.bookStore.rate.passengers && !('person' in this.bookStore.travelers) &&
                    <List>
                        {this.bookStore.rate.passengers.map((pass, i) => (
                            <List.Item
                                key={pass.id}
                                extra={
                                    <Stepper
                                        style={{ width: '100%', minWidth: '100px' }}
                                        showNumber
                                        min={i === 0 ? this.bookStore.rate.minPerBooking : 0}
                                        max={this.bookStore.rate.maxPerBooking === 0 ? 100 : this.bookStore.rate.maxPerBooking}
                                        value={this.bookStore.travelers[pass.ticketCategory]}
                                        onChange={(v) => this.onChangeTravelers(v, pass)}
                                    />}
                            >
                                {pass.title}
                                <span style={{ marginLeft: '10px', fontSize: '14px', color: '#888', verticalAlign: 'sub', lineHeight: '20px' }}>
                                    {pass.price ? `${pass.price.currency} ${pass.price.amount}/${this.bookStore.rate.pricedPerPerson === true ? 'person' : 'total'}` : null}
                                    {this.bookStore.travelers[`${pass.ticketCategory}_tieredPrices`] ? `${this.bookStore.travelers[`${pass.ticketCategory}_tieredPrices`].currency} ${this.bookStore.travelers[`${pass.ticketCategory}_tieredPrices`].amount}/${this.bookStore.rate.pricedPerPerson === true ? 'person' : 'total'}` : null}
                                </span>
                            </List.Item>
                        ))}
                    </List>
                }
                <WhiteSpace />
                <List>
                    <List.Item arrow="horizontal"
                        onClick={() => {
                            document.getElementsByTagName('body')[0].style.overflowY = 'hidden';
                            this.setState({
                                show: true,
                            });
                        }}
                        extra={(this.bookStore.startDate || this.minDate).toLocaleDateString()}
                    >
                        Select date
                        </List.Item>
                    <Calendar
                        prefixCls="am-calendar holly-calendar"
                        type="one"
                        locale={calendar_enUS}
                        visible={this.state.show}
                        onCancel={this.onCancelDate}
                        onConfirm={this.onConfirmDate}
                        // onSelectHasDisableDate={this.onSelectHasDisableDate}
                        getDateExtra={this.disableDate}
                        initalMonths="3"
                        defaultValue={this.bookStore.startDate || this.minDate}
                        defaultDate={this.minDate}
                        minDate={this.minDate}
                        // maxDate={new Date(this.cityStore.tourObj.pricesByDateRange.to)}
                        maxDate={new Date((new Date()).setDate(90))}
                    />
                </List>
                {tour.requiredCustomerFields.includes('passportId') === true &&
                    <Fragment>
                        <WhiteSpace />
                        <List >
                            {/* renderHeader={() => 'Tell us who\'s going on this tour'} */}
                            <List.Item arrow="horizontal" multipleLine onClick={this.onClickEnterTraveler}>
                                Travelers details
                    </List.Item>
                        </List>
                    </Fragment>
                }

                <List renderHeader={() => 'Contact Infomation'}>
                    <InputItem
                        clear
                        // placeholder="Full name as passport order"
                        placeholder="|"
                        onClick={this.onFocus}
                        onChange={(value) => this.fillFullname(value)}
                        onErrorClick={() => this.onErrorClick(this.bookStore.formValidResult.nameRequired)}
                        error={this.bookStore.formValidResult.nameError}
                        defaultValue={this.bookStore.fullname || this.bookStore.passengerList[0].fullname}
                    >Full name</InputItem>
                    <InputItem
                        clear
                        // placeholder="eg. example@trippest.com"
                        placeholder="|"
                        onClick={this.onFocus}
                        onChange={(value) => this.fillEmail(value)}
                        error={this.bookStore.formValidResult.emailError}
                        onErrorClick={() => this.onErrorClick(this.bookStore.formValidResult.emailRequired)}
                        defaultValue={this.bookStore.email}
                    >Email</InputItem>
                    <List.Item arrow="horizontal" multipleLine className="holly-country"
                        extra={`${this.bookStore.country.name} (+${this.bookStore.country.code})`}
                        onClick={this.onClickCountry}>
                        Mobile
                    </List.Item>
                    <InputItem
                        type="phone"
                        clear
                        placeholder="eg. 13138383838"
                        onChange={(value) => this.fillMobile(value)}
                        defaultValue={this.bookStore.mobile}
                        error={this.bookStore.formValidResult.mobileError}
                        onErrorClick={() => this.onErrorClick(this.bookStore.formValidResult.mobileRequired)}
                        onClick={this.onFocus}
                    />
                </List>
                <List renderHeader={() => pickupInfoText}>
                    {(tour.meetingType === 'MEET_ON_LOCATION') && tour.startPoints.length > 0 &&
                        tour.startPoints.map(i => (
                            <Radio.RadioItem key={i.id}
                                name='meetingpoint'
                                style={{ color: '#333' }}
                                className='holly-radio'
                                checked={this.bookStore.pickupOption.pickupAddress === i.title}
                                onChange={() => this.fillPickupAddress(i.title)}
                            >
                                {i.title}<List.Item.Brief>{`${i.address.addressLine1},${i.address.city} ${i.address.postalCode},${i.address.state},${i.address.countryCode}`}</List.Item.Brief>
                            </Radio.RadioItem>
                        ))
                    }
                    {/* {tour.startPoints.length > 0 && */}
                    {(tour.meetingType === 'MEET_ON_LOCATION_OR_PICK_UP' && tour.startPoints.length > 0) &&
                        <Fragment>
                            <Picker
                                dismissText="Cancel"
                                okText="OK"
                                title="pick-up option"
                                extra={null}
                                cols={1}
                                data={pickupOption}
                                onOk={e => this.onSelectPickup(e[0])}
                                value={[this.bookStore.pickupOption.value]}
                                error={true}
                            >
                                <div
                                    style={{ backgroundColor: '#fff', paddingLeft: 15 }}
                                >
                                    <div style={{ display: 'flex', height: '45px', lineHeight: '45px' }}>
                                        <div style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: '#888', fontSize: '17px' }}>
                                            {this.bookStore.pickupOption.label}
                                        </div>
                                        <div style={{ textAlign: 'right', padding: '5.5px 0 11.5px 0', color: '#888', marginRight: 15 }}>{this.bookStore.formValidResult.pickupError ? Icons.WARN : Icons.DOWN}</div>
                                    </div>
                                </div>
                            </Picker>
                            {
                            this.bookStore.pickupOption.value === 'meetingpoint' &&
                                tour.startPoints.map(i => (
                                    <Radio.RadioItem key={i.id}
                                        name='meetingpoint'
                                        style={{ color: '#333' }}
                                        className='holly-radio'
                                        checked={this.bookStore.pickupOption.pickupAddress === i.title}
                                        onChange={() => this.fillPickupAddress(i.title)}
                                    >
                                        {i.title}<List.Item.Brief>{`${i.address.addressLine1},${i.address.city} ${i.address.postalCode},${i.address.state},${i.address.countryCode}`}</List.Item.Brief>
                                    </Radio.RadioItem>
                                ))
                            }
                        </Fragment>
                    }
                    {(tour.meetingType === 'PICK_UP' || (tour.meetingType === 'MEET_ON_LOCATION_OR_PICK_UP' &&
                        this.bookStore.pickupOption.value === 'custom' )
                    ) &&
                        <Fragment>
                            <InputItem placeholder='Hotel name '
                                onClick={this.onFocus}
                                onChange={(value) => this.fillHotelName(value)}
                                defaultValue={this.bookStore.pickupOption.hotelName}
                            />
                            <InputItem placeholder='Hotel address'
                                onClick={this.onFocus}
                                onChange={(value) => this.fillHotelAddress(value)}
                                defaultValue={this.bookStore.pickupOption.hotelAddress}
                            />
                            <InputItem placeholder='Name Under Hotel Reservation'
                                onClick={this.onFocus}
                                onChange={(value) => this.fillCheckinName(value)}
                                defaultValue={this.bookStore.pickupOption.checkInName}
                            />
                        </Fragment>
                    }
                </List>
                <List renderHeader={() => 'Special requirements'}>
                    <TextareaItem
                        onClick={this.onFocus}
                        placeholder="|"
                        data-seed="logId"
                        // ref={el => this.autoFocusInst = el}
                        rows={2}
                        onChange={(value) => this.fillRequests(value)}
                    />
                </List>
                <WhiteSpace size='xl' style={{height: '120px'}} />
                <div style={{ zIndex: 20, borderRadius: 0, width: '100%', color: '#888', position: 'fixed', bottom: 0, display: 'block', backgroundColor: '#f5f5f9', borderTop: '1px solid #ccc' }}>
                    <p style={{padding: '10px', margin: 0}}>By taping below and placing a order, I agree with that I have read and agree to be bound by Trippest's Terms and Conditions.</p>
                <Button type="primary" onClick={this.onClickSubmit}
                    style={{  borderRadius: 0, width: '100%',  display: 'flex', justifyContent: 'space-between', padding: '0 20px' }}>
                    <span>
                        Total:&nbsp;
                    <span>{`$${this.bookStore.totalPrice}`}</span>
                    </span>
                    <span> Pay Now&nbsp;&raquo;</span>
                </Button>
                </div>
            </SecondaryLayout>
        )
    }
}
export default BookingView
