var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import React, { useState, useEffect, useMemo } from "react";
import { MagnifyingGlassIcon } from "@phosphor-icons/react";
import { Form as FormComponent } from "@local-logic/design-system";
import { useTranslation } from "react-i18next";
import { useRootElement } from "../context";
import { Route } from "./Route";
import { NoRoute } from "./NoRoute";
import { Select } from "./Select";
import * as styles from "./styles";
import { browserUtils } from "~/utils";
import { textWithHighlighting } from "~/utils/formatters/textWithHighlighting";
import { TrackingPipelineEvents, AnalyticsEvents, } from "~/sdks/LocalContent/types";
import { useResponsiveBreakpoints } from "~/hooks/useResponsiveBreakpoints";
import { useTracking } from "~/tracking";
import { useAddressSearch } from "~/sdks/LocalContent/hooks/useAddressSearch";
export function Form() {
    const { t } = useTranslation("localContent");
    const tracking = useTracking();
    const breakpoints = useResponsiveBreakpoints();
    const { commuteData, commuteOptions, isCommuteDataLoading, country, location, handleCalculateCommute, } = useRootElement();
    // State for search input field
    const [isFieldFocused, setIsFieldFocused] = useState(false);
    const [searchQuery, setSearchQuery] = useState("");
    const [selectedValue, setSelectedValue] = useState();
    const { data, isLoading } = useAddressSearch({
        query: searchQuery,
        country,
        location,
    });
    useEffect(() => {
        if (typeof (commuteData === null || commuteData === void 0 ? void 0 : commuteData.label) === "string" && commuteData.label !== "") {
            setSelectedValue(commuteData.label);
        }
    }, [commuteData === null || commuteData === void 0 ? void 0 : commuteData.label]);
    const suggestionResults = useMemo(() => !searchQuery
        ? browserUtils.commuteHistory.getSuggestionHistory().slice(0, 3)
        : (data === null || data === void 0 ? void 0 : data.suggestions) || [], [searchQuery, data === null || data === void 0 ? void 0 : data.suggestions]);
    const options = useMemo(() => {
        if (!isFieldFocused || !suggestionResults.length) {
            return [];
        }
        return suggestionResults
            .filter((suggestion) => { var _a; return typeof ((_a = suggestion === null || suggestion === void 0 ? void 0 : suggestion.address) === null || _a === void 0 ? void 0 : _a.description) === "string"; })
            .map((suggestion) => {
            var _a, _b;
            return ({
                value: ((_a = suggestion.address) === null || _a === void 0 ? void 0 : _a.description) || "",
                label: textWithHighlighting(((_b = suggestion.address) === null || _b === void 0 ? void 0 : _b.description) || "", searchQuery),
                key: suggestion.locationId || `address-${suggestion.locationId}`,
            });
        });
    }, [isFieldFocused, searchQuery, suggestionResults]);
    const handleOnSearchChange = (e) => {
        setSearchQuery(e.target.value);
    };
    const handleOnSearchClear = () => {
        handleCalculateCommute(Object.assign(Object.assign({}, commuteOptions), { label: undefined, destination: undefined }));
        setSelectedValue(undefined);
    };
    const handleOnSelect = (value) => __awaiter(this, void 0, void 0, function* () {
        var _a;
        setSelectedValue(value);
        const suggestion = suggestionResults.find((suggestionResult) => { var _a; return ((_a = suggestionResult.address) === null || _a === void 0 ? void 0 : _a.description) === value; });
        if (typeof suggestion === "undefined") {
            return;
        }
        if (typeof ((_a = suggestion === null || suggestion === void 0 ? void 0 : suggestion.address) === null || _a === void 0 ? void 0 : _a.coordinates) !== "undefined") {
            browserUtils.commuteHistory.push(suggestion);
            handleCalculateCommute(Object.assign(Object.assign({}, commuteOptions), { label: value, destination: {
                    lat: suggestion.address.coordinates.latitude,
                    lng: suggestion.address.coordinates.longitude,
                } }));
            const eventAttributes = {
                label: value,
                mode: commuteOptions.commuteType,
                destinationLat: suggestion.address.coordinates.latitude,
                destinationLng: suggestion.address.coordinates.longitude,
            };
            tracking.postEvent({
                eventType: TrackingPipelineEvents.COMMUTE_CALCULATOR_CALCULATE_ROUTE,
                eventAttributes: Object.entries(eventAttributes).map(([key, objectValue]) => ({
                    label: key,
                    data: objectValue,
                })),
            });
            tracking.trackAnalyticsEvent({
                eventName: AnalyticsEvents.COMMUTE_CALCULATOR_CALCULATE_ROUTE,
                eventAttributes,
            });
        }
    });
    const handleOnFieldFocus = () => {
        setIsFieldFocused(true);
    };
    const handleOnFieldBlur = () => {
        setIsFieldFocused(false);
    };
    const handleOnCommuteTypeChange = (value) => {
        handleCalculateCommute(Object.assign(Object.assign({}, commuteOptions), { commuteType: value }));
    };
    return (React.createElement("div", { className: styles.container },
        React.createElement(FormComponent.Root, { initialValues: { searchQuery: "" }, className: styles.form },
            React.createElement(FormComponent.SearchAndSelect, { name: "searchQuery", label: !selectedValue &&
                    !isFieldFocused &&
                    typeof (commuteData === null || commuteData === void 0 ? void 0 : commuteData.label) === "string"
                    ? commuteData.label
                    : t("commute.placeholder"), direction: breakpoints.sm ? "topToBottom" : "bottomToTop", maxLength: 150, clearOnSelect: false, selectedLabel: selectedValue, prefixIcon: MagnifyingGlassIcon, isLoading: isLoading || isCommuteDataLoading, options: options, onChange: handleOnSearchChange, onClear: handleOnSearchClear, onSelect: handleOnSelect, onFocus: handleOnFieldFocus, onBlur: handleOnFieldBlur }),
            React.createElement(Select, { name: "commuteType", selected: commuteOptions.commuteType, onChange: handleOnCommuteTypeChange })),
        React.createElement(Route, { isLoading: isCommuteDataLoading }),
        typeof commuteOptions.destination !== "undefined" &&
            commuteData === null &&
            !isCommuteDataLoading && React.createElement(NoRoute, null)));
}
//# sourceMappingURL=index.js.map