import { Button } from 'react-bootstrap';
import React, { useState } from 'react';
import { useSelector } from 'react-redux';

import styles from './Submit.module.css';
import SubmitForm from './SubmitForm';

const Submit = () => {
    const [show, setShow] = useState(false);
    const { coordinates, drawOnMap } = useSelector(
        (state) => state.coordinatesReducer
    );

    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);

    const calculateLength = () => {
        if (!coordinates || coordinates.length < 2) {
            return 0;
        }

        if (window.google && window.google.maps && window.google.maps.geometry) {
            const length = window.google.maps.geometry.spherical.computeLength(
                coordinates
            );
            return length.toFixed(2);
        }

        return 0;
    };

    const length = calculateLength();

    return (
        <>
            <Button
                variant='success'
                className={styles.submitButton}
                onClick={handleShow}
            >
                Add New
            </Button>
            {drawOnMap && coordinates.length >= 2 && (
                <div className={styles.lengthDisplay}>
                    <span className={styles.lengthLabel}>Length:</span>
                    <span className={styles.lengthValue}>{length} m</span>
                </div>
            )}
            <SubmitForm handleClose={handleClose} show={show} />
        </>
    );
};

export default Submit;
