import {Meteor} from "meteor/meteor"
import React, {FunctionComponent, useEffect, useRef, useState} from "react"
import $ from "jquery"
import {ImagesDB} from "/imports/api/Listings/client/collections/images"
import {EveryspaceLogo} from "/imports/ui/components/icons/EveryspaceLogo";
import {HeaderLoggedInMenuOptions} from "/imports/ui/components/general/HeaderLoggedIn";
import {useTracker} from "meteor/react-meteor-data";
import {
    HeaderSearchModalEmitter,
    InnerModal,
    SearchAddressInput
} from "/imports/ui/components/modals/HeaderSearchModal";
import {getCoordinatesFromAutocompleteLocation} from "/imports/ui/hooks/useLocationsAutocomplete";
import {filtersToQueryParams} from "/imports/ui/components/listings/search/utils/url-filters";
// @ts-ignore
import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
import {AllActivitiesModal} from "/imports/ui/components/modals/AllActivitiesModal";
import UserDropdownMenu from "/imports/ui/components/general/UserDropdownMenu";
import {IconX} from "/imports/ui/components/icons/IconX";
import {IconMenu} from "/imports/ui/components/icons/IconMenu";
import {HeaderSearchAndActivitiesDropdown} from "/imports/ui/components/general/HeaderSearchAndActivitiesDropdown";

interface EveryspaceHeaderProps {
    unreadMessageCount: number
    profileImageReady: boolean
    listingsReady: boolean
    userDataReady: boolean
    profile: {
        city: string
        country_mobile_code: string
        email: string
        first_name: string
        last_name: string
        mobile_number: string
        occupation: string[]
        profile_image_id: string
        subscribed_to_newsletter: boolean
        pictureUrl?: string
    }
    routeName: string
    hasCreatedListing?: boolean
    _id?: string
    user?: any
}

// @ts-ignore
const OffCanvasContent = ({hasCreatedListing, profileIcon, userIsLoggedIn, routeName, mobileMenu }) => {
    let unreadMessageCount;
    let hasBookingNotification;
    const user = useTracker(() => Meteor.user(), []);

    const [showInnerModal, setShowInnerModal] = useState(false);
    const [selectedEvent, setSelectedEvent] = useState("");
    const [selectedLocation, setSelectedLocation] = useState<any>();
    const [showActivitiesModal, setShowActivitiesModal] = useState(false);

    const [showSearchOptions, setShowSearchOptions] = useState(false);

    useEffect(() => {
        // @ts-ignore
        window.setOffCanvasEvent = setSelectedEvent;
        // @ts-ignore
        window.setOffCanvasLocation = setSelectedLocation;
        // @ts-ignore
        window.setShowSearchOptions = setShowSearchOptions;

    }, []);

    if(user) {
        // @ts-ignore
        unreadMessageCount = user.UnreadMessagesCount || 0;
        // @ts-ignore
        hasBookingNotification = user.hostUnreadBookingNotifications || user.filmmakerUnreadBookingNotifications;
    }
    let hasNotification = unreadMessageCount && unreadMessageCount > 0 || (hasBookingNotification && hasBookingNotification.total > 0);


    return <>
        {showActivitiesModal && <AllActivitiesModal onSubmit={(value) => {
            setSelectedEvent(value);
            setShowActivitiesModal(false);
            HeaderSearchModalEmitter.emit("hideAllActivitiesModal");
        }} onClose={() => setShowActivitiesModal(false)}/>}

        <div className="nav-dropdown text-left shadowed"
             style={{ width: '100%', position: 'absolute', right: 0, backgroundColor: 'white', top: 0, fontSize: 16, zIndex: 999 }}>
            {showSearchOptions ?
                <div style={{ padding: "0 16px" }}>
                    <div className="heading bg-off-white text-grey mobile">
                        FIND A SPACE
                    </div>

                    <div style={{ marginBottom: 12 }} />

                    <div className="container">
                        <div className={`form-group`}>
                            <div onClick={() => setShowInnerModal(!showInnerModal)}
                                 style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}
                                 className={`form-input cursor-pointer-hover ${selectedEvent !== "" ? "not-empty":""}`}>

                                {selectedEvent ? selectedEvent.toString():<span style={{ height: 20 }} />}
                                <i className="material-icons">{!showInnerModal ? "keyboard_arrow_down":"keyboard_arrow_up"}</i>

                            </div>
                            <label>What are you planning?</label>
                            <div className={`${showInnerModal ? "":"hide"}`}>
                                <InnerModal onClose={() => setShowInnerModal(false)} onSubmit={(value) => setSelectedEvent(value)} />
                            </div>

                        </div>

                        <SearchAddressInput location={selectedLocation} setLocation={(location) => setSelectedLocation(location)} />

                        <div>
                            <button
                                disabled={!selectedEvent || !selectedLocation}
                                onClick={async () => {
                                    const location = selectedLocation?.type === "popular"
                                        ? selectedLocation.location
                                        : {
                                            name: selectedLocation?.place.description,
                                            center: await getCoordinatesFromAutocompleteLocation(selectedLocation)
                                        };

                                    FlowRouter.go("Search", {}, filtersToQueryParams({
                                        location,
                                        activities: selectedEvent ? [selectedEvent]:null
                                    }));

                                    setShowSearchOptions(false);
                                }}
                                style={{ height: 50 }} className="button honey expanded">
                                Search
                            </button>
                            <button
                                onClick={() => setShowSearchOptions(false)}
                                style={{ marginBottom: 0, height: 50 }} className="button charcoal expanded">
                                Back
                            </button>
                        </div>

                    </div>
                </div>
                :
                userIsLoggedIn ?
                    <>
                        <div className="heading bg-off-white text-grey mobile">
                            My Dashboard
                            <div className={'profile-icon-wrapper mobile text-charcoal'+ (hasNotification ? " has-notification":"")}>
                                {profileIcon}
                            </div>
                        </div>
                        <a href={FlowRouter.path('BookingRequests')} className="nav-item">
                            <i className='material-icons charcoal'>format_list_bulleted</i>
                            Bookings
                            {hasBookingNotification && hasBookingNotification.total > 0 ? <span className="notification-dot"/>:null}
                        </a>
                        <a href={FlowRouter.path('MessagesInbox')} className="nav-item">
                            <i className='material-icons charcoal'>question_answer</i>
                            Messages
                            {unreadMessageCount > 0 ? <span className="notification-dot"/>:null}
                        </a>
                        <a href={FlowRouter.path('HostListingsAll')} className="nav-item">
                            <i className='material-icons charcoal'>apps</i>
                            My Listings
                        </a>
                        <a href={FlowRouter.path('UserFavourites')} className="nav-item mb-16">
                            <i className='material-icons charcoal'>favorite</i>
                            Favourites
                        </a>

                        <div className="heading bg-off-white text-grey">
                            My Account
                        </div>
                        <a href={FlowRouter.path('PaymentsAndPayouts')} className="nav-item">
                            <i className='material-icons charcoal'>settings</i>
                            Account Settings
                        </a>
                        <a href={FlowRouter.path('UserProfile')} className={"nav-item " + (!hasCreatedListing ? "mb-16":"")}>
                            <i className='material-icons charcoal'>account_circle</i>
                            My Profile
                        </a>
                        <div className="nav-button mt-40">
                            <button onClick={() => setShowSearchOptions(true)} className='button font-bold expanded charcoal'>Search</button>
                        </div>

                        <div className="nav-button">
                            <button onClick={() => FlowRouter.go("ListingCreate")} className='button font-bold expanded mint'>List Your Space</button>
                        </div>

                        <div className="nav-button spacing-margin-mobile_80">
                            <button onClick={() => Meteor.logout()} className='button font-bold expanded honey no-margin'>Logout</button>
                        </div>
                    </>
                    :
                    <ul className="vertical menu" style={{ paddingLeft: 12, paddingRight: 12 }}>
                        <li><a data-close="offCanvasLeftOverlap" href='/create-account' className={'link underline white ' + (routeName === 'SignUp' ? 'active':'')}>Sign Up</a></li>
                        <li><a data-close="offCanvasLeftOverlap" href='/login' className={'link underline white ' + (routeName === 'Login' ? 'active':'')}>Log In</a></li>
                        <li className="mb-8"><a target="_blank" href="http://help.everyspace.co.za" className='link underline white'>FAQs</a></li>
                        <li><button onClick={(evt) => {
                            evt.preventDefault();
                            HeaderSearchModalEmitter.emit("showAllActivitiesModal");
                            setShowActivitiesModal(true);
                            mobileMenu("close");
                        }} className='link expanded button honey' style={{ borderRadius: 8, marginBottom: 8 }}>View All Activities</button></li>
                        <li><button onClick={(evt) => {
                            evt.preventDefault();
                            setShowSearchOptions(true)
                        }} className='link expanded button charcoal' style={{ borderRadius: 8, marginBottom: 8 }}>Search</button></li>
                        <li><a data-close="offCanvasLeftOverlap" href={FlowRouter.path('ListingCreate')} className='link button mint' style={{ borderRadius: 8 }}>List Your Space</a></li>
                    </ul>
            }
        </div>
    </>
}

export const EveryspaceHeader: FunctionComponent<EveryspaceHeaderProps> = (props) => {
    // @ts-ignore
    let offCanvasInstance: FoundationSites.OffCanvas | null = null;
    const offCanvasRef = useRef();

    const [hasScrolled, setScrolled] = useState(false);
    const [open, setOpen] = useState(false)

    useEffect(() => {
        const {OffCanvas} = window.Foundation;
        // @ts-ignore
        offCanvasInstance = new OffCanvas($(offCanvasRef.current), {});
        window.addEventListener("scroll", onScroll);
        window.addEventListener("touchmove", onScroll, false);
        // @ts-ignore
        window.toggleOffCanvasButton = () => setOpen(!open);
        return () => {
            window.removeEventListener("scroll", onScroll);
            window.removeEventListener("touchmove", onScroll);
        }
    }, []);

    const onScroll = () => {
        // @ts-ignore
        setScrolled($(window).scrollTop() > 0);
    }

    const mobileMenu = (action: "open" | "close" ) => {
        $("#offCanvasLeftOverlap").foundation(action);
        setOpen(action === "open");
    }

    const profile = props.profile;
    const userIsLoggedIn = !!Meteor.userId();

    let {first_name, last_name} = profile;

    let profileIcon;

    if (props.profileImageReady && profile.profile_image_id) {
        profileIcon = (
            <div className="profile-icon circle mobile"
                 style={{backgroundImage: `url(${ImagesDB.findOne({_id: profile.profile_image_id}).link()})`}}/>
        );
    } else if (profile.pictureUrl) {
        profileIcon = (
            <div className="profile-icon circle mobile" style={{backgroundImage: `url(${profile.pictureUrl})`}}/>
        );
    } else {
        profileIcon = (
            <div className="profile-icon circle mobile">
                <div style={{backgroundColor: "#84CEA3"}}>{first_name.charAt(0) + last_name.charAt(0)}</div>
            </div>
        );
    }

    return <>
        <div
            className={"header-wrapper transparent" + (hasScrolled ? " scrolled" : "")}>
            <div className={"header-bar"}>
                <div className={"grid-container"}>
                    <div className="header">
                        <div className="child-container text-left">
                            <a href={"/"} className={`logo`}>
                                <EveryspaceLogo color={hasScrolled ? "#252729":"#FFFFFF"} />
                            </a>
                        </div>
                        {userIsLoggedIn && props.userDataReady ? <>
                                <div className="child-container right-menu text-right position-relative">
                                    <HeaderLoggedInMenuOptions hasCreatedListing={props.hasCreatedListing} />
                                    <UserDropdownMenu
                                        profileImageReady={props.profileImageReady}
                                        listingsReady={props.listingsReady}
                                        hasCreatedListing={props.hasCreatedListing}
                                        _id={props._id}
                                        profile={props.profile}
                                        {...props.user}
                                    />
                                </div>
                            </>
                            :
                            // @ts-ignore
                            <HeaderSearchAndActivitiesDropdown isTransparentHeader={hasScrolled} routeName={props.routeName} />
                        }


                        <div className="hide-for-medium">
                            <button
                                data-toggle="offCanvasLeftOverlap"
                                onClick={(_evt) => {
                                    // @ts-ignore
                                    setOpen(!open);
                                }}
                                className={hasScrolled ? "text-charcoal":"text-white"}>
                                {open ? <IconX style={{ width: 28, height: 28 }} />:<IconMenu style={{ width: 28, height: 28 }} />}
                            </button>
                        </div>

                    </div>
                </div>

                <div className="off-canvas-wrapper">
                    {/*@ts-ignore*/}
                    <div ref={offCanvasRef}
                         className="off-canvas position-left custom" id="offCanvasLeftOverlap" data-off-canvas
                         data-transition="overlap">
                        <OffCanvasContent
                            mobileMenu={mobileMenu}
                            userIsLoggedIn={userIsLoggedIn}
                            routeName={props.routeName}
                            hasCreatedListing={props.hasCreatedListing}
                            profileIcon={profileIcon}
                        />
                    </div>
                </div>

                <div className='header-bottom-line'/>
            </div>
        </div>
    </>
}
