import { useEffect, useState } from 'react';
import { Button, Form, Modal, Row } from 'react-bootstrap';
import { useDispatch, useSelector } from 'react-redux';
import { useForm } from 'react-hook-form';
import { addNewCable } from '../../../../store/asyncMethods/cableMethod';
import { reset } from '../../../../store/reducers/coordinatesReducer';
import CableMapping from './CableMapping';

const CableCreate = ({ show, handleClose }) => {
  const dispatch = useDispatch();
  const [cableMap, setCableMap] = useState([]);
  const { register, handleSubmit, watch, setValue } = useForm();

  const { startNode, endNode, coordinates } = useSelector(
    (state) => state.coordinatesReducer
  );

  useEffect(() => {
    setValue('cable_type', 'none');
    setValue('fiber_count', 'NaN');
    setValue('tube_count', 'NaN');
    setValue(
      'cable_distance',
      window.google.maps.geometry.spherical
        .computeLength(coordinates)
        .toFixed(2)
    );
  }, [coordinates, setValue]);

  const onSubmitHandler = (data) => {
    if (cableMap) {
      data.fiber_mapping = cableMap;
    }
    dispatch(
      addNewCable(data, () => {
        dispatch(reset());
        handleClose();
      })
    );
  };

  return (
    <Modal show={show} onHide={handleClose} size='lg'>
      <Form onSubmit={handleSubmit(onSubmitHandler)}>
        <Modal.Header closeButton>
          <Modal.Title>Create Cable</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Row>
            <Form.Group className='col'>
              <Form.Label className='mb-0'>Start Node</Form.Label>
              <Form.Control
                disabled
                value={
                  startNode
                    ? `${startNode.name} (${startNode.id}: ${startNode.type})`
                    : 'noting selected as Start Node'
                }
              />
            </Form.Group>
            <Form.Group className='col'>
              <Form.Label className='mb-0'>End Node</Form.Label>
              <Form.Control
                disabled
                value={
                  endNode
                    ? `${endNode.name} (${endNode.id}: ${endNode.type})`
                    : 'noting selected as End Node'
                }
              />
            </Form.Group>
            <Form.Group className='col'>
              <Form.Label className='mb-0'>Distance</Form.Label>
              <Form.Control
                disabled
                value={
                  window.google.maps.geometry.spherical
                    .computeLength(coordinates)
                    .toFixed(2) + ' M'
                }
              />
            </Form.Group>
          </Row>
          <hr />
          <Row>
            <Form.Group className='col'>
              <Form.Label className='mb-0'>Name</Form.Label>
              <Form.Control
                placeholder='Cable Name'
                {...register('name', { required: 'Name is required.' })}
              />
            </Form.Group>
            <Form.Group className='col'>
              {' '}
              <Form.Label className='mb-0'>Cable Type</Form.Label>
              <Form.Select
                {...register('cable_type', {
                  required: 'Cable type is required',
                })}
                defaultValue='none'
              >
                <option value='none'>None</option>
                <option value='tight-buffered'>Tight Buffered</option>
                <option value='loose-tube-buffered'>Loose Tube Buffered</option>
              </Form.Select>
            </Form.Group>
          </Row>
          <Row className='mt-3'>
            <Form.Group className='col'>
              <Form.Label className='mb-0'>Cable Tube</Form.Label>
              <Form.Select
                {...register('tube_count', {
                  required: 'Cable tube is required.',
                  valueAsNumber: true,
                })}
                defaultValue='none'
              >
                <option value='none'>None</option>
                <option value='1'>1</option>
                <option value='2'>2</option>
                <option value='3'>3</option>
                <option value='4'>4</option>
                <option value='5'>5</option>
                <option value='6'>6</option>
                <option value='7'>7</option>
                <option value='8'>8</option>
                <option value='9'>9</option>
                <option value='10'>10</option>
                <option value='11'>11</option>
                <option value='12'>12</option>
              </Form.Select>
            </Form.Group>
            <Form.Group className='col'>
              <Form.Label className='mb-0'>Fiber Core</Form.Label>
              <Form.Select
                {...register('fiber_count', {
                  required: 'Cable Fiber is required.',
                  valueAsNumber: true,
                })}
                defaultValue='none'
              >
                <option value='none'>None</option>
                <option value='1'>1</option>
                <option value='2'>2</option>
                <option value='3'>3</option>
                <option value='4'>4</option>
                <option value='5'>5</option>
                <option value='6'>6</option>
                <option value='7'>7</option>
                <option value='8'>8</option>
                <option value='9'>9</option>
                <option value='10'>10</option>
                <option value='11'>11</option>
                <option value='12'>12</option>
              </Form.Select>
            </Form.Group>
          </Row>
          <Form.Group className='col mt-2'>
            <Form.Label className='mb-0'>Length/m</Form.Label>
            <Form.Control
              placeholder='Enter Cable Length'
              {...register('cable_length', {
                required: 'Cable Length is required.',
                valueAsNumber: true,
              })}
            />
          </Form.Group>
          <Form.Group className='mt-3'>
            <Form.Control
              as='textarea'
              row={4}
              placeholder='Remarks'
              {...register('remarks', { defaultValue: 'hello world' })}
            />
          </Form.Group>

          {startNode.type === 'cable' &&
            watch('cable_type') !== 'none' &&
            !isNaN(watch('fiber_count')) &&
            !isNaN(watch('tube_count')) && (
              <Form.Group>
                <hr className='mb-0' />
                <CableMapping
                  cableMap={cableMap}
                  setCableMap={setCableMap}
                  cableType={watch('cable_type')}
                  fiberCount={watch('fiber_count')}
                  tubeCount={watch('tube_count')}
                />
              </Form.Group>
            )}
        </Modal.Body>
        <Modal.Footer>
          <Button variant='secondary' onClick={handleClose}>
            Close
          </Button>
          <Button variant='primary' type='submit'>
            Submit
          </Button>
        </Modal.Footer>
      </Form>
    </Modal>
  );
};

export default CableCreate;
