import { useEffect, useState } from 'react';
import {
    Badge,
    Button,
    ButtonGroup,
    Container,
    Row,
    Table,
} from 'react-bootstrap';
import { MdCable } from 'react-icons/md';
import _ from 'lodash';

import { ConnectedComponent } from './ConnectedComponent';
import axiosInstance from '../../../../../../util/axiosInstance';
import { getColor, getHex } from '../../../../../../util/colorModule';
import { VscDebugDisconnect } from 'react-icons/vsc';
import { useDispatch } from 'react-redux';
import {
    deleteOnuFromCluster,
    disconnectOnuInterface,
} from '../../../../../../store/asyncMethods/onuMethod';
import { UpdateOnuDetail } from './UpdateOnuDetail';

const OnuDetail = ({ selectedDevice }) => {
    const dispatch = useDispatch();
    const [onuDetail, setOnuDetail] = useState(null);

    useEffect(() => {
        if (selectedDevice === null) return;

        const fetchOnuDetail = async () => {
            try {
                const { data } = await axiosInstance.get(
                    `/onus/${selectedDevice.id}/detail`
                );
                setOnuDetail(data);
            } catch (error) {
                console.log(error.message);
            }
        };
        fetchOnuDetail();
    }, [selectedDevice]);

    const onDisconnectHandler = (disconnectType) => {
        if (!window.confirm('Are you sure you want to disconnect?')) return;
        dispatch(
            disconnectOnuInterface(disconnectType, onuDetail.id, () => {
                setOnuDetail((prevState) => {
                    const updatedState = { ...prevState };
                    if (['fiber', 'optical'].includes(disconnectType)) {
                        updatedState.fiber = null;
                        updatedState.optical_connected_component = null;
                    } else {
                        updatedState.lan_connected_component = null;
                    }

                    return updatedState;
                });
            })
        );
    };

    const deleteOnuHandler = () => {
        if (!window.confirm('Are you sure you want to delete this onu?'))
            return;
        dispatch(
            deleteOnuFromCluster(onuDetail.id, () => {
                setOnuDetail(null);
            })
        );
    };

    return (
        onuDetail && (
            <Container fluid>
                <Table striped bordered hover className='mt-3'>
                    <tbody>
                        <tr>
                            <td>Onu Id</td>
                            <td>{onuDetail.id}</td>
                        </tr>
                        <tr>
                            <td>Name</td>
                            <td>{onuDetail.name}</td>
                        </tr>
                        <tr>
                            <td>manufactures</td>
                            <td>{onuDetail.manufactures}</td>
                        </tr>
                        <tr>
                            <td>Device Model</td>
                            <td>{onuDetail.model}</td>
                        </tr>
                        <tr>
                            <td>Serial Number</td>
                            <td>{onuDetail.serial_number}</td>
                        </tr>
                        <tr>
                            <td>Remarks</td>
                            <td>{onuDetail.remarks}</td>
                        </tr>
                    </tbody>
                </Table>
                <ButtonGroup className='mb-1 btn-group-sm'>
                    <UpdateOnuDetail
                        onuDetail={onuDetail}
                        setOnuDetail={setOnuDetail}
                    />
                    <Button variant='danger' onClick={deleteOnuHandler}>
                        Delete
                    </Button>
                </ButtonGroup>
                <hr className='my-1' />
                <Row>
                    {onuDetail.fiber ? (
                        <div className='p-3 bg-light rounded shadow-sm mb-3 col-6'>
                            <MdCable className='h4 m-0' title='Optical' />{' '}
                            {onuDetail.fiber.cable.id}.{' '}
                            {onuDetail.fiber.cable.name}(
                            {onuDetail.fiber.fiber_number}:
                            {_.toUpper(getColor(onuDetail.fiber.fiber_number))}{' '}
                            <span
                                style={{
                                    backgroundColor: getHex(
                                        onuDetail.fiber.fiber_number
                                    ),
                                    height: '10px',
                                    width: '10px',
                                    display: 'inline-block',
                                }}
                                className='rounded-circle'
                            />
                            )
                            {onuDetail.fiber && (
                                <Badge
                                    pill
                                    className='ms-1'
                                    bg='danger'
                                    role='button'
                                    onClick={() => onDisconnectHandler('fiber')}
                                >
                                    <VscDebugDisconnect />
                                </Badge>
                            )}
                        </div>
                    ) : (
                        <ConnectedComponent
                            connected_component={
                                onuDetail?.optical_connected_component
                            }
                            onDisconnectHandler={onDisconnectHandler}
                            interfaceType='optical'
                        />
                    )}

                    <ConnectedComponent
                        connected_component={onuDetail?.lan_connected_component}
                        onDisconnectHandler={onDisconnectHandler}
                        interfaceType='lan'
                    />
                </Row>
            </Container>
        )
    );
};

export default OnuDetail;
