import React, {FunctionComponent, useEffect, useState} from "react";
import {Meteor} from "meteor/meteor";
import {sc} from "/imports/ui/components/general/forms/SchemaWrappedComponents";
import {PaymentFailedPrompt} from "/imports/ui/components/prompts/PaymentFailedPrompt";
import {PeachPayForm} from "/imports/ui/components/bookings/PeachPayForm";
import {useSchema} from "/imports/ui/hooks/useSchema";
import {BookingRequestUserDetailsSchema} from "/imports/api/Bookings/both/schemas/BookingSchema";
// @ts-ignore
import $ from "jquery/dist/jquery";
// @ts-ignore
import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
import {PersonalDetailsContainer} from "/imports/ui/components/listing-detail/ListingDetailGallery";
import _ from "lodash";
import {ActivitiesParentEnum, ActivitiesSubEnum} from "/imports/api/Activities/both/enums";
import {AllActivitiesModal} from "/imports/ui/components/modals/AllActivitiesModal";

interface ActivitiesFormProps {
    bookingDetails: any
    setFormSubmitted: (arg: boolean) => any
    setAttendees: (arg: any) => any
    setBookingDetails: (arg: any) => any
    formSubmitted: boolean
    listing: any
}

const scrollToViewFunc = () => {
    const { top } = $("#form-top").offset();
    $("html, body").animate({ scrollTop: top - 200 });
}

export const getMinAndMaxAttendeesForListing = (listing: any) => {
    const { pricing_tiers, maxAttendees } = listing;
    let minAttendees = pricing_tiers[0].min;

    return [minAttendees, maxAttendees];
}

// @ts-ignore
const ActivityListTile = ({ onSubmit, title, currentActive, selectAllSubItems }) => {

    const [open, setOpen] = useState(false);
    const [childIsSelected, setChildIsSelected] = useState(false);

    useEffect(() => {
        const arr = ActivitiesSubEnum[title];

        if(selectAllSubItems) {
            if(title === currentActive) {
                setChildIsSelected(true);
            } else {
                setChildIsSelected(false);
            }
        } else {
            if(_.findIndex(arr, (val) => {
                return val === currentActive
            }) !== -1) {
                setChildIsSelected(true);
            } else {
                setChildIsSelected(false);
            }
        }

    }, [currentActive]);

    return <div className={`main-dropdown-tile ${childIsSelected ? "active":""}`} onClick={() => {
        setOpen(!open);
    }}>
        <div onClick={() => {
            if (selectAllSubItems) {
                onSubmit(title);
            }
        }}>
            <span className={`circle ${childIsSelected ? "active":""}`} />
            {title}
        </div>

        <i className={`material-icons ${open || childIsSelected ? "text-white":"text-mint"}`}>keyboard_arrow_right</i>

        {open &&
        <div className="sub-dropdown main-dropdown activities">
            {_.map(ActivitiesSubEnum[title], sub => {
                return <div className="tile" onClick={() => {
                    if (selectAllSubItems) {
                        onSubmit(title);
                    } else {
                        onSubmit(sub);
                    }
                }}>
                    <div>
                        <span className={`square ${sub === currentActive || (childIsSelected && selectAllSubItems) ? "active":""}`} />
                        {sub}
                    </div>
                </div>
            })}
        </div>
        }
    </div>
}

// @ts-ignore
export const ActivityDropdown = ({ onClose, onSubmit, currentActive, selectAllSubItems = false, customCloseReveal = false }) => {
    return <div className="relative-modal main-dropdown">
        <div className="dropdown-header-card" style={{ zIndex: 6 }}>
            <div className="title-bar">
                WHAT ARE YOU PLANNING?
            </div>

            <div style={{ marginBottom: 12 }} />

            <div>
                {_.map(ActivitiesParentEnum, value => {
                    return <ActivityListTile key={`activity_list_tile_${value}`} currentActive={currentActive} onSubmit={onSubmit} title={value} selectAllSubItems={selectAllSubItems}  />
                })}
            </div>
        </div>

        {customCloseReveal ? null:<div onClick={onClose} style={{zIndex: 5, position: "fixed", inset: 0}}/>}
    </div>
}

export const ActivitiesForm: FunctionComponent<ActivitiesFormProps> = ({ listing, setAttendees, bookingDetails, setBookingDetails, setFormSubmitted }) => {

    const form = useSchema(BookingRequestUserDetailsSchema, bookingDetails);

    const { paymentError, messageThreadId } = FlowRouter.current().queryParams;

    const [, setPeachPaymentsFormHasLoaded] = useState(false);
    const [showActivityDropdown, setShowActivityDropdown] = useState(false);
    const [selectedActivity, setSelectedActivity] = useState("Activity Type");
    const [preBookingId, setPreBookingId] = useState(FlowRouter.current().queryParams.preBookingId);

    useEffect(() => {
        if(bookingDetails.activityType) {
            setSelectedActivity(bookingDetails.activityType);
        }
        scrollToViewFunc();
    }, [ JSON.stringify(bookingDetails) ]);

    const [minAttendees, maxAttendees] = getMinAndMaxAttendeesForListing(listing);
    const tooManyAttendees = form.getValue("exactAttendees") > maxAttendees;
    const tooFewAttendees = form.getValue("exactAttendees") < minAttendees;

    return <div id={"form-top"}>
        <button onClick={() => {
            setFormSubmitted(false);
            setBookingDetails({});
        }} className="back-to-listing-profile-button">
            <i className="material-icons text-honey">arrow_back</i>
            Back to Listing Overview
        </button>
        <h1 className="request-booking-form-title">Booking Form</h1>

        <div className='divider mb-40' />

        {!preBookingId ?
            <form onSubmit={(evt) => {
                evt.preventDefault();
                Meteor.call("bookings.create", {...bookingDetails, ...form.getValues()}, listing._id, messageThreadId, (err: any, preBookingId: any) => {
                    if (err) {
                        console.error(err);
                    } else {
                        setPreBookingId(preBookingId);
                    }
                });
            }}>
                <div className='charcoal-header-block'>
                    Booking Details
                </div>

                <div className={"grid-x grid-margin-x"}>
                    <div className="cell large-6">
                        <div className="form-group">
                            <div>
                                {showActivityDropdown && <AllActivitiesModal onClose={() => setShowActivityDropdown(false)} onSubmit={(val) => {
                                    setSelectedActivity(val);
                                    form.setValue("activityType", val);
                                    setShowActivityDropdown(false);
                                }} />}

                                <div className={`activity-request-booking-dropdown ${showActivityDropdown || form.getValue("activityType") !== "" ? "active":""}`} onClick={() => setShowActivityDropdown(true)}>
                                    {selectedActivity}
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="cell large-6">
                        <sc.FormInput errorMessage={null} field={form.field("activityName")} />
                    </div>

                </div>

                <sc.FormInput
                    type={"number"}
                    errorMessage={tooManyAttendees ? "That's more attendees than this listing caters for!":tooFewAttendees ? "That's less than this listing has specified as a minimum":""}
                    field={form.field("exactAttendees")}
                    className={`${form.getValue("exactAttendees") ? "not-empty":""} ${tooManyAttendees || tooFewAttendees && form.getValue("exactAttendees") ? "invalid":""}`}
                    onChange={(evt: { target: { value: any; }; }) => {
                        const value = evt.target.value;
                        const sanitized = value.replace(/[^0-9]/g, '');
                        form.setValue("exactAttendees", sanitized);
                        setAttendees(sanitized);
                    }}
                />

                <sc.FormTextArea
                    label={"Activity Description"}
                    errorMessage={null}
                    className={"textarea-fixed-width mt-8 min-height-100 " + (form.getValue("activityDescription") !== "" ? "not-empty":"")}
                    field={form.field("activityDescription")}

                />

                <div className='charcoal-header-block mt-40'>
                    Personal Details
                </div>

                <div className="mt-24">
                    <PersonalDetailsContainer userId={Meteor.userId()} />

                    <div className="mt-32" />
                    <span className="textarea-heading">We’d love to get to know you. Please tell us a bit more about you and your team.</span>
                    <sc.FormTextArea
                        errorMessage={null}
                        className={"textarea-fixed-width min-height-100 mt-8 " + (form.getValue("userPersonalDetails") !== "" ? "not-empty":"")}
                        field={form.field("userPersonalDetails")}
                        label={""}
                    />
                </div>

                <div className="width-container-wrapper">
                    <div className="mt-60">
                        <button
                            onClick={() => {
                                const $peachPaymentsPayButton = $(".wpwl-button-pay");
                                $peachPaymentsPayButton.trigger("click");
                                scrollToViewFunc();
                            }}
                            disabled={!form.isValid() || tooManyAttendees || tooFewAttendees}
                            className="button honey expanded"
                        >
                            <i className="material-icons text-white mr-4">check_circle</i>
                            CONTINUE BOOKING REQUEST
                        </button>
                    </div>

                </div>

            </form>
            :
            null
        }

        {preBookingId &&
            <>
                <div className='charcoal-header-block' style={{ marginBottom: 24, marginTop: 0 }}>
                    Payment Details
                </div>

                <p className="payment-prompt" style={{ marginBottom: 16 }}>
                    We think trust is kind of a big deal.
                    That’s why you’ll only be charged once the host accepts your booking.
                </p>

                {paymentError ?
                    <div className="margin-bottom-1">
                        <PaymentFailedPrompt />
                    </div>
                    :
                    null
                }

                <PeachPayForm
                    onReady={() => setPeachPaymentsFormHasLoaded(true)}
                    action={FlowRouter.path("BookingPeachPaymentsResult", { listingId: listing._id, preBookingId })}
                    method={"bookings.preparePeachPaymentCheckout"}
                    methodArgs={{ preBookingId }} />

                <p className="text-grey mt-20 mb-24 text-center">
                    By submitting the booking request you agree
                    to the <span onClick={() => window.open("/Location_Agreement_Standard_Terms_FINAL.pdf")} className="display-inline-block cursor-pointer-hover text-dark-mint">Booking Agreement</span>,
                    you agree to our terms of service, the rules set out by the host and
                    you agree to pay the total amount once the owner approves the booking.
                </p>

                <div id="tips" className='content-footer-block' style={{ marginBottom: 30 }}>
                    <div className='icon'>
                        <img src="/images/confused_woman.png" alt="alt"/>
                    </div>
                    <div className='bar-left'>
                        <h2 className='content-footer-header'>What Happens Next?</h2>
                        <div className='content-footer-entry'>
                            <p className='content-footer-copy'>
                                The host will have 3 days to accept or deny your booking request.
                                If the host accepts your booking request, you will be charged the full amount.
                            </p>
                            <p className='content-footer-copy'>
                                If you cancel outside of 48 hours from the start of the booking,
                                you will receive a 50% refund. Cancellations within 48 hours are non-refundable.
                                You can find out more about our <span onClick={() => window.open("https://intercom.help/everyspace-092ff11f1464/en/articles/6001818-what-is-the-cancellation-refund-policy")} className="display-inline-block text-dark-mint cursor-pointer-hover">Cancellation Policy</span>.
                            </p>
                        </div>
                    </div>
                </div>
            </>
        }
    </div>
}
