import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "@emotion/react/jsx-runtime";
import { Box, HStack, Icon, IconButton, Modal, ModalContent, ModalOverlay, Text, useDisclosure, } from "@chakra-ui/react";
import { MapPin } from "@feedloop/icon";
import dynamic from "next/dynamic";
import Script from "next/script";
import React from "react";
import InputComponentLabel from "../components/InputComponentLabel";
import { LocationNotActivatedModal, PreviewMapInput, SearchInput, useMapboxAPI, } from "../components/map";
import useDisableCondition from "../hooks/useDisableCondition";
import { useEvaluate } from "../hooks/useExpression";
import { registerComponent } from "../interfaces";
import { getShades } from "../registeredThemes/shadeCalculator";
import { RuntimeContext } from "../RuntimeContext";
import { useRuntimeInput } from "../RuntimeInput";
const Map = dynamic(() => import("../components/map/mapbox-map.map"), {
    ssr: false,
});
const LocationMapInput = registerComponent("Location Map Input", {
    type: "none",
    icon: "LocationInput",
    group: "input",
    display: "inline",
    defaultProps: {
        label: "Location Input",
        hidden: false,
        placeholder: "Placeholder here",
        data: {
            inputID: "location",
            field: { type: "point", options: {} },
            validation: {
                required: false,
            },
        },
        previewMap: false,
    },
    propDefinition: {
        label: { group: "Design", type: "expression", options: {} },
        placeholder: {
            group: "Design",
            type: "expression",
            options: {},
        },
        hidden: { group: "Design", type: "boolean", options: {} },
        data: {
            group: "Design",
            type: "state",
            options: {
                inputID: "location",
                field: { type: "point", options: {} },
            },
        },
        previewMap: {
            group: "Design",
            type: "boolean",
            options: {},
        },
    },
    Component: (props) => {
        var _a, _b, _c;
        const theme = RuntimeContext.useSelectState((s) => s.theme);
        const { isOpen, onClose, onOpen } = useDisclosure();
        const { isOpen: isLocationErrorModalOpen, onClose: onLocationErrorModalClose, onOpen: onLocationErrorModalOpen, } = useDisclosure();
        const title = useEvaluate(props.properties.label);
        const placeholder = useEvaluate(props.properties.placeholder);
        const [isCurrentLocation, setIsCurrentLocation] = React.useState(false);
        const data = useRuntimeInput(props.properties.data, props.data.page.row, {
            validate: (value) => {
                if (typeof value === "undefined") {
                    return { error: "" };
                }
                else if (!value) {
                    return { error: "Required field, Please enter the data" };
                }
            },
        });
        const mapboxAPI = useMapboxAPI();
        const { data: mapData } = mapboxAPI.useSearch(data.value
            ? `${data.value.coordinates[0]},${data.value.coordinates[1]}`
            : "", {
            limit: 1,
        });
        // @ts-ignore
        const { isDisabled } = useDisableCondition(props.instance);
        const disabledProperties = {
            border: "1px solid rgb(226, 232, 240)",
            pointerEvents: isDisabled ? "none" : "auto",
            background: isDisabled && "#E7E7E7",
            color: isDisabled && "#A2A2A2",
        };
        const handleModalClose = React.useCallback(() => {
            onClose();
        }, []);
        const defaultValue = (!!mapData && ((_a = mapData === null || mapData === void 0 ? void 0 : mapData.features[0]) === null || _a === void 0 ? void 0 : _a.text)) ||
            (data.value
                ? `${data.value.coordinates[0]},${data.value.coordinates[1]}`
                : "");
        const getisCurrentLocation = React.useCallback(() => {
            if (navigator.geolocation && !!data.value) {
                navigator.geolocation.getCurrentPosition((position) => {
                    setIsCurrentLocation(position.coords.longitude === data.value.coordinates[0] &&
                        position.coords.latitude === data.value.coordinates[1]);
                }, () => {
                    setIsCurrentLocation(false);
                });
            }
        }, [data.value]);
        const handleDataChange = React.useCallback((lng, lat) => {
            data.onChange({
                type: "Point",
                coordinates: [lng, lat],
            });
        }, []);
        const getLocation = () => {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition((position) => {
                    handleDataChange(position.coords.longitude, position.coords.latitude);
                    setIsCurrentLocation(true);
                }, () => {
                    setIsCurrentLocation(false);
                    onLocationErrorModalOpen();
                });
            }
        };
        React.useEffect(() => {
            getisCurrentLocation();
            return () => {
                setIsCurrentLocation(false);
            };
        }, [getisCurrentLocation]);
        return (_jsxs(_Fragment, { children: [_jsx(Script, { src: "https://api.mapbox.com/mapbox-gl-js/v2.11.0/mapbox-gl.js" }), _jsx(Script, { src: "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v5.0.0/mapbox-gl-geocoder.min.js" }), _jsxs(Box, Object.assign({ display: props.properties.hidden ? "none" : undefined }, { children: [props.properties.previewMap ? (_jsx(PreviewMapInput, { label: title, locationLabel: (!!mapData && ((_b = mapData === null || mapData === void 0 ? void 0 : mapData.features[0]) === null || _b === void 0 ? void 0 : _b.text)) ||
                                (data.value
                                    ? `${data.value.coordinates[0]},${data.value.coordinates[1]}`
                                    : ""), onEdit: () => {
                                onOpen();
                            }, location: data.value && data.value.coordinates })) : (_jsxs(_Fragment, { children: [_jsx(InputComponentLabel, { title: title, name: "location", isRequired: (_c = props.properties.data.validation) === null || _c === void 0 ? void 0 : _c.required, isEmpty: title.length === 0 }), _jsxs(HStack, { children: [_jsx(Box, Object.assign({ onClick: onOpen, flex: 1 }, { children: _jsx(SearchInput, { style: disabledProperties, placeholder: placeholder, name: props.properties.data.inputID, value: defaultValue }, props.properties.data.inputID) })), _jsx(IconButton, { "aria-label": "locate", variant: "outline", icon: _jsx(Icon, { as: MapPin }), onClick: getLocation, color: isCurrentLocation ? theme.options.primaryColor : "black", border: isCurrentLocation
                                                ? `1px solid ${theme.options.primaryColor}`
                                                : "none", bg: isCurrentLocation
                                                ? getShades(theme.options.primaryColor)[50]
                                                : "surface.900" })] })] })), !!data.validation.error && (_jsx(Text, Object.assign({ fontSize: "sm", color: "red", "data-test": "location-input-error" }, { children: data.validation.error }))), _jsxs(Modal, Object.assign({ isOpen: isOpen, onClose: handleModalClose, trapFocus: false, blockScrollOnMount: true }, { children: [_jsx(ModalOverlay, {}), _jsx(ModalContent, Object.assign({ position: "absolute", bottom: 0, margin: 0, h: "full", bg: "#F6F6F6", w: { base: "full", lg: "3xl" }, maxWidth: {
                                        base: "full",
                                        lg: "3xl",
                                    } }, { children: _jsx(React.Suspense, Object.assign({ fallback: _jsx("span", { children: "loading" }) }, { children: _jsx(Map, { styles: {
                                                w: "full",
                                                h: "100vh",
                                            }, onBackClick: onClose, onChange: (lng, lat) => {
                                                handleDataChange(lng, lat);
                                                handleModalClose();
                                            }, defaultMarker: data.value && data.value.coordinates, placeholder: placeholder, name: props.properties.data.inputID, defaultValue: defaultValue }, props.properties.data.inputID) })) }))] })), _jsx(LocationNotActivatedModal, { onClose: onLocationErrorModalClose, isOpen: isLocationErrorModalOpen })] }))] }));
    },
});
export default LocationMapInput;
//# sourceMappingURL=buildLocationMapInput.js.map