import React from 'react';
import {Meteor} from "meteor/meteor";
import numeral from "numeral";
import "moment-round";
import {TimeslotDateInputService} from "../../../api/Bookings/both/TimeslotDateInputService";
import {useSchema} from "../../hooks/useSchema";
import {DateTimeslotInput} from "./DateTimeslotInput";
import {UserImageContainer} from "../general/asdasd";
import {Option, Select} from "../general/Select";
import Tooltip from "../general/Tooltip";
import {useTracker} from "meteor/react-meteor-data";
import {PricingService} from "../../../api/Bookings/both/services/PricingService";
import {RequestBookingFormSchema} from "../../../api/Bookings/both/schemas/RequestBookingFormSchema";
import {TimeslotSchema} from "../../../api/Bookings/both/schemas/TimeslotSchema";
import {FlowRouter} from "meteor/ostrio:flow-router-extra";
import {ActiveCampaignEvents} from "../../../api/ActiveCampaign/both/method-calls-wrapper";
import {PromotionTooltip} from "/imports/ui/components/test/PromotionTooltip";
import {PreferredHours} from "/imports/ui/components/tooltips/PreferredHours";
import {EveryspaceIntercomClient} from "/imports/api/Intercom/both/lib/EveryspaceIntercomClient";

export const RequestBookingForm = ({ revealRef, listingId, listingStatus, listingPublished, fees, calendar, createdBy, setBookingDetails, toggleBookingForm, bookingDetails, additionalFees }) => {

    const { messageThreadId } = FlowRouter.current().queryParams;

    const bookingForm = useSchema(RequestBookingFormSchema, bookingDetails);
    const [ loaded, userData ] = useTracker(() => {
        return [
            Meteor.subscribe("userProfile", createdBy).ready(),
            Meteor.users.findOne({_id: createdBy})
        ];
    }, [ createdBy ]);

    const rate = bookingDetails.customRate ?
        bookingDetails.customRate
        :
        bookingForm.getValue("attendees").price;

    const pricingService = new PricingService()
        .setAdditionalFees(additionalFees)
        .setHoursFromTimeslots(bookingForm.getValue("timeslots"))
        .setDiscount(bookingForm.getValue("attendees").custom_discount)
        .setRate(rate);

    const listingMinDuration = bookingDetails.canOverrideMinHours ?
        1
        :
        bookingForm.getValue("attendees").hours
            ?
            bookingForm.getValue("attendees").hours
            :
            1;

    const service = new TimeslotDateInputService(listingMinDuration);

    const onRemoveTimeslot = (index) => {
        let timeslots = bookingForm.getValue("timeslots");
        let secondHalfOfArray = timeslots.splice(index+1, timeslots.length);
        let firstHalfOfArray = timeslots.splice(0, index);
        bookingForm.setValue("timeslots", _.union(firstHalfOfArray, secondHalfOfArray));
    }

    //Display Logic
    let price, hours, discount;

    if (!bookingForm.getValue("attendees")) {
        if (fees.length) {
            price = fees[0].price;
            hours = fees[0].hours;
            discount = fees[0].custom_discount;
        } else {
            price = 0
            hours = 0;
            discount = 0;
        }
    } else {
        price = bookingForm.getValue("attendees").price;
        hours = bookingForm.getValue("attendees").hours;
        discount = bookingForm.getValue("attendees").custom_discount;
    }

    //End of Display Logic
    fees = [null, ...fees];

    const dateError = _.find(bookingForm.getErrors(), (err) => err.name.includes("timeslots"));

    let invalidTimeFrame = null;
    if (dateError) {
        let array = bookingForm.getValue("timeslots");
        let arrayLen = array.length;
        if (array[arrayLen - 1].end) {
            invalidTimeFrame = dateError.name.includes("end");
        }
    }

    const minHoursNotMet = hours > pricingService.getHours();

    /**
     * Check whether or not to disable the form
     */
    const isTheHost = Meteor.userId() === createdBy;
    const isFormDisabled = isTheHost || listingStatus !== "active" || !listingPublished;

    if (!loaded) {
        return null;
    }

    if (!userData) {
        console.log("This listing's creator was not found in the user database");
        return null;
    }

    return (
        <div className={'request-booking-form'}>
            <div className="form-light-border padding-24">

                <div className="form-header text-center">
                    <h2 className='text-charcoal display-inline-block'>R {price}/hr</h2>
                    <div />
                    <PreferredHours hours={hours} />
                </div>

                {discount && discount !== 0
                    ? <>
                        <div className='divider mt-16 mb-20' />

                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                            <Tooltip
                                options={{ position: 'top', alignment: 'center' }}
                                clickOpen={true}
                                disableHover={true}
                                scrollElementSelector={null}
                                toolTipText={`<div>This host offers a discount for longer bookings. Stretch your budget and get extra hours for less.</div>`}
                                render={(ref) => (
                                    <h4 className='margin-bottom-0'>
                                        8+ hour discount <button ref={ref} type="button" className="pricing-listing-tooltip" style={{ paddingTop: 0, marginBottom: 1 }}><i className='material-icons text-charcoal mr-8'>info</i></button>
                                    </h4>
                                )} />

                            <div className="pill">{discount}% off</div>
                        </div>
                    </>
                    :null}

                <div className='divider mt-20 mb-20' />

                <form
                    onSubmit={(evt) => {
                        evt.preventDefault();
                        setBookingDetails(bookingForm.getValues());
                    }}
                    className={'form-fields-container' + (isFormDisabled ? " pointer-events-none":"")}>

                    {_.map(bookingForm.getValue("timeslots"), (value, index) => {
                        return <DateTimeslotInput
                            key={index}
                            onRemoveClick={index === 0 ? () => bookingForm.setValue("timeslots", [TimeslotSchema.clean({})]):() => onRemoveTimeslot(index)}
                            form={bookingForm}
                            index={index}
                            service={service}
                            calendar={calendar}
                        />
                    })}

                    {
                        !dateError ?
                            <div className="display-inline">
                                <span>&nbsp;</span>
                                <span className="total-hours">Total Hours: {pricingService.getHours()}</span>
                            </div>
                            :
                            null
                    }

                    <button type="button" disabled={dateError} onClick={() => {
                        bookingForm.addToList("timeslots", TimeslotSchema.clean({}));
                        bookingForm.setValue("attendees", "");
                    }} className={"add-a-day text-dark-mint"}>
                        <i className={"material-icons text-dark-mint"}>add</i>
                        Add a day
                    </button>

                    <div className={"mt-28 form-group margin-bottom-0"} id={"selectContainer"}>
                        <span className={'select-label select-label-position-over' + (bookingForm.getValue("attendees") ? " select-has-value":"")}>Attendees</span>
                        <Select
                            className={"margin-bottom-0 time-select crew-size" + (bookingForm.getValue("attendees") ? " not-empty":"")}
                            hasHollowArrowDropdown={true}
                            value={bookingForm.getValue("attendees")}
                            renderActive={(active) => {
                                if(!active) return ( <div className="text-left" >&nbsp;</div>);
                                return (
                                    <div className="text-left">
                                        {active.label}
                                        <span className="float-right price">R {active.price} / hr</span>
                                    </div>
                                )
                            }}
                            onChange={(value) => {
                                bookingForm.setValue("attendees", value);
                            }}>

                            {_.map(fees, (value, index) => {
                                if (!value) return <Option key={"SelectAttendees"} value={null}>Attendees</Option>
                                return <Option
                                    selected={value.label === bookingForm.getValue("attendees").label}
                                    value={value}
                                    key={index}>
                                    <div className="text-left">
                                        {value.label}
                                        <span className="float-right price">R {value.price} / hr</span>
                                    </div>
                                </Option>
                            })}
                        </Select>

                    </div>

                    <div>
                        <span className="error-message">
                            {invalidTimeFrame ? "Invalid Timeframe":null}
                        </span>
                        <span className="error-message">
                            {
                                bookingForm.getValue("attendees") ?
                                    bookingForm.getErrorMessage("attendees")
                                    :
                                    null
                            }
                        </span>
                    </div>

                    {bookingForm.isValid() ?
                        <div className="pricing-container">
                            <div className="price-item-wrapper">
                                <span className="price-label">R {pricingService.getRate()} x {pricingService.getHours()} hours</span>
                                <span className="price-total">R {numeral(pricingService.getBookingFee()).format("0,0.00")}</span>
                            </div>
                            {
                                _.map(additionalFees, ({ name, price }) => {
                                    return <div key={name} className="price-item-wrapper">
                                        <span className="price-label">{name}</span>
                                        <span className="price-total">R {numeral(price).format("0,0.00")}</span>
                                    </div>
                                })
                            }
                            <div className="price-item-wrapper">
                                <span className="price-label">Service Fee</span>
                                <Tooltip
                                    options={{ position: 'top', alignment: 'center' }}
                                    toolTipText={"This covers costs that allow Everyspace to complete your\n" +
                                    "transaction and provide support for your booking."}
                                    render={(ref) => (
                                        <button
                                            ref={ref}
                                            type={"button"}
                                            onClick={(evt) => console.log(evt.target)} className="pricing-listing-tooltip">
                                            <i className="material-icons">info</i>
                                        </button>
                                    )} />

                                <span className="price-total">
                                    R {numeral(pricingService.getFilmmakerServiceFee().getVATInclAmount()).format("0,0.00")}
                                </span>
                            </div>

                            <div className="price-item-wrapper">
                                <span className="price-label rose">8+ hour discount</span>
                                <span className="price-total rose">
                                    - R {numeral(pricingService.getTotalDiscountedAmount()).format("0,0.00")}
                                </span>
                            </div>

                            {/*PROMOTION_FEATURE*/}
                            <div className="price-item-wrapper">
                                <span className="price-label rose">Promotion</span>
                                <PromotionTooltip
                                    amount={numeral(pricingService.getFilmmakerServiceFee().getVATInclAmount()).format("0,0.00")}
                                />
                            </div>

                            <div className="total-price-verify-booking" style={{ marginTop: 12 }}>
                                <div>
                                    <span className="price-label font-bold">Total Price</span>
                                    <span className="price-total text-charcoal font-bold float-right">
                                        {/*PROMOTION_FEATURE*/}
                                        R {numeral(pricingService.getTotal() - pricingService.getFilmmakerServiceFee().getVATInclAmount()).format("0,0.00")}
                                    </span>
                                </div>
                            </div>

                            {minHoursNotMet &&
                                <div className="prompt" style={{ marginTop: 12 }}>
                                    <i className="material-icons text-honey">info</i>
                                    <h4 className="font-bold">Minimum hours not met</h4>
                                    <p>
                                        Hosts are more likely to accept your booking request if it meets the minimum number of hours required.
                                    </p>
                                </div>
                            }
                        </div>
                        :
                        null
                    }

                    <div>
                        <button
                            className='button honey expanded box-shadow-button'
                            type="submit"
                            onClick={(evt) => {
                                if (!Meteor.user()) {
                                    FlowRouter.go("Login");
                                }
                                setBookingDetails(bookingForm.getValues());
                                toggleBookingForm();
                                EveryspaceIntercomClient.trackEvent({
                                    eventName: "booking_step_1_completed",
                                    createdAt: Date.now()
                                })
                            }}
                            disabled={!bookingForm.isValid()}
                            style={{marginTop: 32, marginBottom: 12}}>
                            Request Booking
                        </button>
                    </div>

                    <div>
                        {messageThreadId ?
                            <a
                                className={'button dark-mint-on-white border-dark-mint expanded'}
                                href={Meteor.user() ? FlowRouter.path("InboxMessageThread", { threadId: messageThreadId }):FlowRouter.path("Login")}
                                style={{marginBottom: '24px', fontSize: 16}}>
                                Message Host
                            </a>
                            :
                            <button
                                type={"button"}
                                className='button dark-mint hollow expanded box-shadow-button'
                                onClick={() => {
                                    if (!Meteor.user()) {
                                        FlowRouter.go("Login");
                                    }
                                    revealRef.current.open();
                                }}
                                style={{ marginBottom: '24px' }}>
                                Message Host
                            </button>
                        }
                    </div>
                </form>

                <UserImageContainer userId={createdBy} />

            </div>
        </div>
    );
};