import React, {useState} from 'react';
import {Meteor} from "meteor/meteor";
import {useTracker} from "meteor/react-meteor-data";
import {FlowRouter} from "meteor/ostrio:flow-router-extra";
import {ProfileImageSrc} from "../users/dashboard/NotifyActiveListingReveal";
import {DateTimeslotInput} from "../test/DateTimeslotInput";
import {Option, Select} from "../general/Select";
import {sc} from "../general/forms/SchemaWrappedComponents";
import Reveal from "../general/Reveal";
import {useSchema} from "../../hooks/useSchema";
import {PricingService} from "../../../api/Bookings/both/services/PricingService";
import {ContactHostNewMessageThreadFormSchema} from "../../../api/Bookings/both/schemas/ContactHostNewMessageThreadFormSchema";
import {TimeslotDateInputService} from "../../../api/Bookings/both/TimeslotDateInputService";
import {ListingsDB} from "../../../api/Listings/both/collections/listings";
import {TimeslotSchema} from "../../../api/Bookings/both/schemas/TimeslotSchema";
import {ActivityDropdown} from "/imports/ui/components/listing-detail/ActivitiesForm";
import {AllActivitiesModal} from "/imports/ui/components/modals/AllActivitiesModal";

export const ContactHostNewMessageThreadReveal = ({ instance, listingId, initialValues }) => {

    const [
        { calendar, pricing_tiers },
        userDataLoaded,
        userData
    ] = useTracker(() => {
        const listing = ListingsDB.findOne({_id: listingId})

        const userDataLoaded = Meteor.subscribe("userProfile", listing.createdBy).ready();
        const userData = Meteor.users.findOne({ _id: listing.createdBy });

        return [
            listing,
            userDataLoaded,
            userData
        ];
    }, []);

    const [showActivityDropdown, setShowActivityDropdown] = useState(false);
    const [selectedActivity, setSelectedActivity] = useState("Activity Type");

    const hostNegotiationForm = useSchema(ContactHostNewMessageThreadFormSchema, initialValues);

    let contactUsDuration = new PricingService()
        .setHoursFromTimeslots(hostNegotiationForm.getValue("timeslots"))
        .getHours();

    // This is to say there is a minimum of a 1 hour booking
    let timeslotInputService;
    if (hostNegotiationForm.getValue("attendees")) {
        timeslotInputService = new TimeslotDateInputService(hostNegotiationForm.getValue("attendees").hours);
    } else {
        timeslotInputService = new TimeslotDateInputService(1);
    }

    const dateHostError = _.find(hostNegotiationForm.getErrors(), (err) => err.name.includes("timeslots"));

    let invalidTimeFrame = null;
    if (dateHostError) {
        let array = hostNegotiationForm.getValue("timeslots");
        let arrayLen = array.length;
        if (array[arrayLen - 1].end) {
            invalidTimeFrame = dateHostError.name.includes("end");
        }
    }

    const onRemoveContactHostTimeslot = (index) => {
        let timeslots = hostNegotiationForm.getValue("timeslots");
        let secondHalfOfArray = timeslots.splice(index+1, timeslots.length);
        let firstHalfOfArray = timeslots.splice(0, index);
        hostNegotiationForm.setValue("timeslots", _.union(firstHalfOfArray, secondHalfOfArray));
    }

    if(!userDataLoaded) return null;

    return (
        <div>
            <Reveal
                className="dashboard-reveal overflow-y-unset request-booking-form top-40-mobile"
                instance={(reveal) => {
                    this.reveal = reveal;
                    instance(reveal)
                }}>
                <form onSubmit={(evt) => {
                    evt.preventDefault();
                    Meteor.call("Messaging.createThread", listingId, hostNegotiationForm.getValues(), (err, threadId) => {
                        if(err) console.log(err);
                        else FlowRouter.go('InboxMessageThread', { threadId });
                    });
                }}>

                    <div className="reveal-header text-center reveal-header-pattern-green">
                        <div className="modal-icon">
                            {userData.profile.profile_image_id ?
                                <ProfileImageSrc _id={userData.profile.profile_image_id} />
                                :
                                <div className='profile-icon circle dashboard-reveal'>{userData.profile.first_name.charAt(0)  + " " + userData.profile.last_name.charAt(0)}</div>
                            }
                        </div>
                        <button type="button" className="button clear" onClick={() => { this.reveal.close() } }>
                            <i className="material-icons">close</i>
                        </button>
                    </div>

                    <div className="reveal-body form-fields-container bg-white" style={{ paddingBottom: 19, paddingLeft: 24, paddingRight: 24 }}>
                        <h1 className="text-center font-semi-bold">Contact Host </h1>
                        <hr className="divider" style={{ marginTop: 24, marginBottom: 20 }} />
                        {_.map(hostNegotiationForm.getValue("timeslots"), (value, index) => {
                            return <DateTimeslotInput
                                key={index}
                                onRemoveClick={index === 0 ? () => hostNegotiationForm.setValue("timeslots", [TimeslotSchema.clean({})]):() => onRemoveContactHostTimeslot(index)}
                                form={hostNegotiationForm}
                                index={index}
                                service={timeslotInputService}
                                calendar={calendar}
                            />
                        })}

                        <div className="display-inline">
                            <span>&nbsp;</span>
                            <span className="total-hours">Total Hours: {contactUsDuration}</span>
                        </div>

                        <button type="button" disabled={dateHostError} onClick={() => hostNegotiationForm.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 field={hostNegotiationForm.field("flexibleDatesAndTime")} label={"Dates & Times are flexible"} />
                        </div>

                        <div className={"form-group margin-bottom-0"} style={{ marginTop: -9, paddingTop: 0 }} >
                            <div style={{ marginBottom: 28 }}>
                                {showActivityDropdown && <AllActivitiesModal onClose={() => setShowActivityDropdown(false)} onSubmit={(val) => {
                                    setSelectedActivity(val);
                                    hostNegotiationForm.setValue("activityType", val);
                                    setShowActivityDropdown(false);
                                }} />}

                                <div className={`activity-request-booking-dropdown ${showActivityDropdown || hostNegotiationForm.getValue("activityType") !== "" ? "active":""}`} onClick={() => setShowActivityDropdown(true)}>
                                    {selectedActivity}
                                </div>
                            </div>

                            <sc.FormTextArea className={"textarea-fixed-width mt-8 " + (hostNegotiationForm.getValue("message") !== "" ? "not-empty":"")} field={hostNegotiationForm.field("message")} label={"YOUR MESSAGE"} />

                            <div>
                                <span className="error-message">
                                    {invalidTimeFrame ? "Date is invalid":null}
                                </span>
                                <span className="error-message">
                                    {
                                        hostNegotiationForm.getValue("attendees") ?
                                            hostNegotiationForm.getErrorMessage("attendees")
                                            :
                                            null
                                    }
                                </span>
                            </div>

                            <button
                                disabled={!hostNegotiationForm.isValid() && !hostNegotiationForm.getValue("flexibleDatesAndTime")}
                                className="button honey expanded box-shadow-button"
                                type={"submit"}
                            >
                                SEND MESSAGE
                            </button>
                            <button type={"button"} className="button white-on-mint expanded mt-8" onClick={() => {this.reveal.close()}}>
                                Cancel
                            </button>

                        </div>
                    </div>

                </form>
            </Reveal>
        </div>
    );
};