import React, { useState } from "react";
import styles from "./LocateCoordinate.module.css";
import { Button, Form } from "react-bootstrap";
import useLocateCoordinate from "../../../hooks/useLocateCoordinate";
import toast from "react-hot-toast";

export const LocateCoordinateBox = () => {
    const [coordinateText, setCoordinateText] = useState("");
    const { coordinate, locateCoordinateHandler, locateCoordinateClear } =
        useLocateCoordinate();

    const inputBoxHandler = (event) => setCoordinateText(event.target.value);

    const locateInputHandler = () => {
        const [latitude, longitude] = coordinateText
            .split(",")
            .map((coord) => parseFloat(coord.trim()));

        if (!isNaN(latitude) && !isNaN(longitude)) {
            const coordinateObject = { lat: latitude, lng: longitude };

            locateCoordinateHandler(coordinateObject);
        } else {
            toast.error(
                "Invalid coordinate format. Please enter coordinates as 'lat, long'."
            );
        }
    };

    return (
        <div className={styles.locateCoordinateBox}>
            <Form.Control
                type="text"
                placeholder="Enter Lat, Long"
                onChange={inputBoxHandler}
                value={coordinateText}
            />
            {!coordinate ? (
                <Button
                    variant="success"
                    className="ms-1"
                    onClick={locateInputHandler}
                >
                    Locate
                </Button>
            ) : (
                <Button
                    variant="danger"
                    className="ms-1"
                    onClick={() => {
                        locateCoordinateClear();
                        setCoordinateText("");
                    }}
                >
                    Clear
                </Button>
            )}
        </div>
    );
};
