import React, {useRef, useLayoutEffect, useEffect, useState} from 'react';
import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
import SimpleSchema from "simpl-schema";
import moment from "moment";
import numeral from "numeral";
import "moment-round";
import {useSchema} from "../../../hooks/useSchema";

import {DateTimeslotInput} from "../../test/DateTimeslotInput";
import { Option, Select } from "../../general/Select";
import {TimeslotDateInputService} from "/imports/api/Bookings/both/TimeslotDateInputService";
import _ from "lodash";
import {Meteor} from "meteor/meteor";
import Tooltip from "../../general/Tooltip";
import {PricingService} from "/imports/api/Bookings/both/services/PricingService";
import {AmendedFeeFormReveal} from "../../messages/reveals/AmendedFeeFormReveal";
import {PromotionTooltip} from "/imports/ui/components/test/PromotionTooltip";
import {sc} from "/imports/ui/components/general/forms/SchemaWrappedComponents";
import {FormCheckboxMint} from "/imports/ui/components/general/forms/FormCheckboxes";
import {BookingSchema} from "/imports/ui/components/users/dashboard/RequestCustomFeeSchemas";
import {AllActivitiesModal} from "/imports/ui/components/modals/AllActivitiesModal";

export const RequestCustomFeeForm = ({ discussionService }) => {

    const bookingDetails = discussionService.getBookingDetails();
    const hasReceivedCustomRate = discussionService.getHasCustomFee();
    const hostId = discussionService.getHostId();
    const listing = discussionService.getListing();
    const fees = discussionService.getFeesArray();
    const threadId = discussionService.getThreadId();
    const isHost = Meteor.userId() === hostId;

    const bookingForm = useSchema(BookingSchema, bookingDetails);

    const [showActivityDropdown, setShowActivityDropdown] = useState(false);

    const amendedFeeFormRef = useRef();

    //Check if component has rendered already, if it has reset the price as an update was called manipulating the timeslots of the booking.
    const firstUpdate = useRef(true);
    useLayoutEffect(() => {
        if (firstUpdate.current) {
            firstUpdate.current = false;
            return;
        }
        if (bookingForm.isValid()) {
            discussionService.setBookingDetails({...bookingForm.getValues()});
        }
    }, [ bookingForm.getValues() ]);


    const { additional_fees: additionalFees, name, address, pricing_tiers } = listing;

    const dateError = _.find(bookingForm.getErrors(), (err) => err.name.includes("timeslots"));
    const service = new TimeslotDateInputService(1);

    let { timeslots } = bookingDetails;
    const { calendar, status, published } = listing;

    if (bookingForm.getValue("timeslots")) {
        timeslots = bookingForm.getValue("timeslots");
    }

    const rate = discussionService.getHasCustomFee() ? bookingDetails.customRate:pricing_tiers[0].price;

    const pricing = new PricingService()
        .setAdditionalFees(additionalFees)
        .setHoursFromTimeslots(timeslots)
        .setDiscount(pricing_tiers[0].custom_discount)
        .setRate(rate);

    let bookingDuration = pricing.getHours();

    let hasDateError = false;
    for (let i = 0; i < calendar.length; i++) {
        for (let k = 0; k < timeslots.length; k++) {
            if (moment(timeslots[k].day).isSame(calendar[i].date, "day")) {
                hasDateError = true;
            }
        }
    }

    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));
    }

    let displayAddress = '';
    if(address) {
        displayAddress = discussionService.getDisplayAddress(address);
    }

    const isRequestButtonDisabled = status !== "active" || !published;

    return (
        <div style={{ paddingLeft: 24 }}>
            <div className='request-booking-form message-thread-fee-amend-form box-shadow-none'>
                <div className="padding-24">
                    <h2 onClick={() => FlowRouter.go("ListingDetail", { listingId: listing._id })} className="title cursor-pointer-hover" style={{ marginBottom: 8 }}>{name}</h2>
                    <h4 className="subtitle">{displayAddress}</h4>

                    <form onSubmit={(evt) => {
                        evt.preventDefault();
                        // Meteor.call("bookings.create", {...bookingDetails}, listing._id);
                        // FlowRouter.go("BookingRequests");
                    }}>

                        <div className="form-fields-container" style={{ paddingBottom: 16 }}>
                            {_.map(bookingForm.getValue("timeslots"), (value, index) => {
                                return <DateTimeslotInput
                                    disabled={isHost}
                                    key={index}
                                    onRemoveClick={index === 0 || isHost ? null:() => onRemoveTimeslot(index)}
                                    form={bookingForm}
                                    index={index}
                                    service={service}
                                    calendar={calendar}
                                    isMessageThread={isHost}
                                />
                            })}

                            {bookingForm.isValid() ?
                                <div className="display-inline">
                                    <span>&nbsp;</span>
                                    <span className="total-hours">Total Hours: {bookingDuration}</span>
                                </div>
                                :
                                null
                            }

                            {isHost ?
                                null
                                :
                                <button type="button" disabled={dateError} onClick={() => bookingForm.addToList("timeslots", {})} className={"add-a-day text-dark-mint"}>
                                    <i className={"material-icons text-dark-mint"}>add</i>
                                    Add a day
                                </button>
                            }

                            <div style={{ marginTop: 16 }}>
                                <sc.FormMintCheckbox disabled={isHost} field={bookingForm.field("flexibleDatesAndTime")} label={"Dates & Times are flexible"} />
                            </div>

                            <div style={{ marginTop: 23 }}>
                                <div style={{ marginBottom: 12 }}>

                                    {bookingForm.getValue("activityType") &&
                                        <div className={"form-group margin-bottom-0"}>
                                            <span className='text-uppercase text-grey select-label'>Activity Type</span>
                                            <div>
                                                {showActivityDropdown && <AllActivitiesModal onClose={() => setShowActivityDropdown(false)} onSubmit={(val) => {
                                                    bookingForm.setValue("activityType", val);
                                                    setShowActivityDropdown(false);
                                                }} />}

                                                <div style={{ marginBottom: 28 }}>
                                                    <div onClick={() => {
                                                        if(!isHost) {
                                                            setShowActivityDropdown(true)
                                                        }
                                                    }} className={`activity-request-booking-dropdown ${bookingForm.getValue("activityType") !== "" ? "active":""}`}>
                                                        {bookingForm.getValue("activityType")}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    }


                                    <span className={"error-message" + (bookingForm.getValue("timeslots").length > 1 ? "":" display-none")}>
                                        {dateError || hasDateError ? "Date is invalid":null}
                                    </span>

                                    <span className={"error-message" + (!!bookingForm.getValue("message") ? "":" display-none")}>
                                        {bookingForm.getErrorMessage("message")}
                                    </span>

                                    {bookingForm.isValid() && !hasDateError ?
                                        <div className="pricing-container">
                                            <div className="price-item-wrapper">
                                            <span className="price-label">
                                                R {rate.toFixed(2)} x {bookingDuration} hours {hasReceivedCustomRate ? <span className="text-grey" style={{ fontSize: 12 }}>* Custom Fee</span>:null}</span>
                                                <span className="price-total">R {numeral(pricing.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
                                                <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}
                                                            onClick={(evt) => console.log(evt.target)} className="pricing-listing-tooltip">
                                                            <i className="material-icons">info</i>
                                                        </button>
                                                    )} />
                                            </span>
                                            <span className="price-total">
                                            {isHost ?
                                                "- R " + numeral(pricing.getHostServiceFee().getVATInclAmount()).format("0,0.00")
                                                :
                                                "R " + numeral(pricing.getFilmmakerServiceFee().getVATInclAmount()).format("0,0.00")
                                            }
                                            </span>
                                            </div>

                                            {pricing.getDiscount() > 0 && <div className="price-item-wrapper">
                                                <span className="price-label rose">8+ hr discount</span>

                                                <span className="price-total rose">
                                                    - R {numeral(pricing.getTotalDiscountedAmount()).format("0,0.00")}
                                                </span>
                                            </div>
                                            }

                                            {!isHost &&
                                                <>
                                                    {/*PROMOTION_FEATURE*/}
                                                    <div className="price-item-wrapper">
                                                        <span className="price-label rose">Promotion</span>
                                                        <PromotionTooltip
                                                            amount={numeral(pricing.getFilmmakerServiceFee().getVATInclAmount()).format("0,0.00")}
                                                        />
                                                    </div>
                                                </>
                                            }

                                            {isHost ?
                                                <>
                                                    <div className="total-price-verify-booking">
                                                        <div>
                                                            <span className="price-label text-dark-mint font-bold">
                                                                Your Payout
                                                                <Tooltip
                                                                    options={{ position: 'top', alignment: 'center' }}
                                                                    toolTipText={"This is the total payout amount you will receive once the booking is successfully completed."}
                                                                    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>
                                                                <span className="price-total text-dark-mint font-bold float-right">
                                                                R {numeral(pricing.getPayout()).format("0,0.00")}
                                                            </span>
                                                        </div>
                                                        <div>
                                                        </div>
                                                    </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">
                                                        R {numeral(pricing.getTotal() - pricing.getFilmmakerServiceFee().getVATInclAmount()).format("0,0.00")}
                                                    </span>
                                                    </div>
                                                </div>
                                            }
                                        </div>
                                        :
                                        null
                                    }
                                </div>

                                {isHost ?
                                    <button
                                        // disabled={!bookingForm.isValid()}
                                        onClick={() => amendedFeeFormRef.current.open()}
                                        className="button honey expanded box-shadow-button margin-bottom-0"
                                        type={"button"}
                                    >
                                        {hasReceivedCustomRate ? "UPDATE CUSTOM FEE":"SEND CUSTOM RATE"}
                                    </button>
                                    :
                                    <button
                                        onClick={() => {
                                            discussionService.setBookingDetails(bookingForm.getValues());
                                            FlowRouter.go('ListingDetail', { listingId: listing._id }, { messageThreadId: threadId })
                                        }}
                                        disabled={isRequestButtonDisabled || hasDateError || !bookingForm.isValid()}
                                        className={"button honey expanded box-shadow-button margin-bottom-0"}
                                        type={"button"}>
                                            {hasReceivedCustomRate ? "ACCEPT & REQUEST BOOKING":"REQUEST BOOKING"}
                                    </button>


                                }
                            </div>
                        </div>

                    </form>


                    <AmendedFeeFormReveal
                        amendedFeeFormRef={amendedFeeFormRef}
                        discussionService={discussionService}
                    />

                </div>
            </div>
        </div>
    );
};