"use client";
import React, { useMemo } from "react";
import { useFormContext } from "react-hook-form";
import { FormFieldProps, useFormGroupName } from "react-compose-form";
import { InputControl } from "@/components/form/control/input.control";
import { MapPicker } from "@/components/ui/map-picker";

export type MapFieldProps = FormFieldProps<{
    label?: string;
}>;

export const MapControl: React.FC<MapFieldProps> = (props) => {
    const {
        watch,
        setValue
    } = useFormContext();

    const latName = useFormGroupName("lat"),
          lngName = useFormGroupName("lng"),
          lat = watch(latName),
          lng = watch(lngName);

    const position = useMemo(() => {
        if(!lat || !lng) {
            return undefined;
        }

        return { lat, lng };
    }, [lat, lng]);

    return (
        <React.Fragment>
            <InputControl type="hidden" name="lat" />
            <InputControl type="hidden" name="lng" />

            <div className="flex flex-col gap-2">
                {props.label && (
                    <label className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
                        {props.label}
                    </label>
                )}

                <MapPicker
                  position={position}
                  onChange={(position) => {
                    setValue(latName, position.lat, {
                        shouldDirty: true
                    });
                    setValue(lngName, position.lng, {
                        shouldDirty: true
                    });
                  }} />
            </div>
        </React.Fragment>
    );
};
