import { useCallback, useEffect, useState } from 'react';
import { Button, ButtonGroup, Modal } from 'react-bootstrap';
import CableDetail from './CableDetail';
import axiosInstance from '../../../../../util/axiosInstance';
import FiberDetailView from './FiberDetailView';
import { useDispatch } from 'react-redux';
import {
    deleteCableMap,
    disconnectFiber,
} from '../../../../../store/asyncMethods/cableMethod';

const CableInfo = ({ show, setShow, cable }) => {
    const dispatch = useDispatch();
    const [cableDetail, setCableDetail] = useState(null);

    const fetchCableDetail = useCallback(async () => {
        const { data } = await axiosInstance.get(`/cables/${cable.id}/detail`);
        setCableDetail(data);
    }, [cable.id]);

    useEffect(() => {
        if (show) {
            fetchCableDetail();
        } else setCableDetail(null);
    }, [cable.id, fetchCableDetail, show]);

    const handleFiberDisconnect = (fiberId) => {
        if (!window.confirm('Are you sure you want to disconnect?')) return;
        dispatch(disconnectFiber(fiberId, fetchCableDetail));
    };

    const deleteOnuHandler = () => {
        if (!window.confirm('Are you sure you want to delete?')) return;
        dispatch(deleteCableMap(cable.id, () => setShow(false)));
    };

    return (
        cableDetail && (
            <Modal show={show} fullscreen={true} onHide={() => setShow(false)}>
                <Modal.Header closeButton>
                    <Modal.Title>{cable.name} - Cable</Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    <CableDetail cableDetail={cableDetail} />
                    <ButtonGroup className='mb-1 btn-group-sm'>
                        <Button variant='warning'>Update</Button>
                        <Button variant='danger' onClick={deleteOnuHandler}>
                            Delete
                        </Button>
                    </ButtonGroup>
                    <hr />
                    <FiberDetailView
                        cableDetail={cableDetail}
                        handleFiberDisconnect={handleFiberDisconnect}
                    />
                </Modal.Body>
            </Modal>
        )
    );
};

export default CableInfo;
