import { InfoWindow, Polyline } from '@react-google-maps/api';
import { useEffect, useState } from 'react';
import { Badge } from 'react-bootstrap';

import useEditablePolyline from '../../../../hooks/useEditablePolyline';
import CableInfo from './CableDetail/CableInfo';
import getRandomColor from '../../../../util/randomColor';

const Cable = ({ cable }) => {
  const [show, setShow] = useState(false);
  const { name, cable_type, cable_length } = cable;
  const { setParent } = useEditablePolyline();

  const [showInfoWindow, setShowInfoWindow] = useState(false);
  const [position, setPosition] = useState(null);

  const [color, setColor] = useState('#00000');

  useEffect(() => {
    setColor(getRandomColor());
  }, []);

  const options = {
    geodesic: true,
    strokeColor: color,
    strokeOpacity: 1.0,
    strokeWeight: 4,
  };

  const onDblClickHandler = (event) => {
    setParent(cable, event.latLng);
  };

  return (
    <>
      <Polyline
        options={options}
        path={JSON.parse(cable.coordinates)}
        onDblClick={onDblClickHandler}
        onRightClick={({ latLng }) => {
          setPosition(latLng);
          setShowInfoWindow(true);
        }}
      />
      {showInfoWindow && (
        <InfoWindow
          position={position}
          onCloseClick={() => setShowInfoWindow(false)}
        >
          <>
            <p className='mb-1 fw-bold'>{name}</p>
            <hr className='my-1' />
            <p className='mb-1'>
              <span className='fw-bold'>Cable Type</span> {cable_type}
            </p>
            <p className='mb-1'>
              <span className=' fw-bold'>Distance:</span> {cable_length}m
            </p>
            <Badge
              variant='primary'
              size='sm'
              type='button'
              onClick={() => setShow(true)}
            >
              Open Detail View
            </Badge>
          </>
        </InfoWindow>
      )}
      <CableInfo show={show} setShow={setShow} cable={cable} />
    </>
  );
};

export default Cable;
