import { useEffect, useState } from 'react';
import {
    Badge,
    Button,
    ButtonGroup,
    Container,
    Row,
    Table,
    Modal,
    Form,
} from 'react-bootstrap';

import { toast } from 'react-hot-toast';
import axiosInstance from '../../../../../../util/axiosInstance';
import { getColor } from '../../../../../../util/colorModule';
import { MdCable } from 'react-icons/md';
import { SplitterOutputFiber } from './SplitterOutputFiber';
import { ParentComponent } from './ParentComponent';
import { useDispatch } from 'react-redux';
import {
    deleteSplitterFromCluster,
    disconnectSplitterOutput,
    disconnectSplitterParent,
    updateSplitterDetail,
} from '../../../../../../store/asyncMethods/splitterMethod';
import { VscDebugDisconnect } from 'react-icons/vsc';

function UpdateSplitterInfo({ splitterDetail, setSpitterDetail }) {
    const dispatch = useDispatch();
    const splitterOldData = {
        name: splitterDetail.name,
        remarks: splitterDetail.remarks,
    };
    const [splitterNewData, setSplitterNewData] = useState(splitterOldData);

    const [show, setShow] = useState(false);

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

    const onChangeHandler = (e) => {
        setSplitterNewData({
            ...splitterNewData,
            [e.target.name]: e.target.value,
        });
    };

    const onSubmitHandler = async (e) => {
        e.preventDefault();
        const newSplitter = {
            name: splitterNewData.name,
            remarks: splitterNewData.remarks,
        };

        dispatch(
            updateSplitterDetail(splitterDetail.id, newSplitter, (newData) => {
                handleClose();
                setSpitterDetail((prevState) => {
                    return {
                        ...prevState,
                        name: newData.name,
                        remarks: newData.remarks,
                    };
                });
            })
        );
    };

    return (
        <>
            <Button variant='warning' onClick={handleShow}>
                Update
            </Button>
            <Modal show={show} onHide={handleClose}>
                <Modal.Header closeButton>
                    <Modal.Title>Update Splitter Info</Modal.Title>
                </Modal.Header>
                <Form onSubmit={onSubmitHandler}>
                    <Modal.Body>
                        <Form.Group className='mb-3'>
                            <Form.Control
                                type='text'
                                placeholder='Splitter Name'
                                name='name'
                                onChange={onChangeHandler}
                                value={splitterNewData.name}
                            />
                        </Form.Group>
                        <Form.Group className='mb-3'>
                            <Form.Control
                                as='textarea'
                                placeholder='Remarks'
                                rows={3}
                                name='remarks'
                                onChange={onChangeHandler}
                                value={splitterNewData.remarks}
                            />
                        </Form.Group>
                    </Modal.Body>
                    <Modal.Footer>
                        <Button variant='secondary' onClick={handleClose}>
                            Close
                        </Button>
                        <Button variant='primary' type='submit'>
                            Save Changes
                        </Button>
                    </Modal.Footer>
                </Form>
            </Modal>
        </>
    );
}

const SplitterDetail = ({ selectedSplitter }) => {
    const dispatch = useDispatch();
    const [splitterDetail, setSpitterDetail] = useState(null);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const { data } = await axiosInstance.get(
                    '/splitters/' + selectedSplitter.id
                );
                setSpitterDetail(data);
            } catch (error) {
                toast.error(error.message);
            }
        };
        fetchData();
    }, [selectedSplitter]);

    const onDeleteHandler = () => {
        if (!window.confirm('Are you sure you want to delete this splitter?'))
            return;
        dispatch(
            deleteSplitterFromCluster(splitterDetail.id, () => {
                setSpitterDetail(null);
            })
        );
    };

    const onParentDisconnectHandler = () => {
        const isConfirm = !window.confirm(
            'Are you sure you want to disconnect this splitter from its parent?'
        );
        if (isConfirm) return;

        dispatch(
            disconnectSplitterParent(splitterDetail.id, () => {
                setSpitterDetail((prevState) => {
                    return {
                        ...prevState,
                        connected_component: null,
                        fiber: null,
                    };
                });
            })
        );
    };

    const onDisconnectSplitterOutput = (splitterOutId) => {
        if (
            !window.confirm(
                'Are you sure you want to disconnect this splitter output?'
            )
        )
            return;

        dispatch(
            disconnectSplitterOutput(splitterOutId, () => {
                setSpitterDetail((prevState) => {
                    const prev = { ...prevState };
                    const splitterOut = prev.splitter_out.findIndex(
                        (out) => out.id === splitterOutId
                    );
                    prev.splitter_out[splitterOut].fiber = null;
                    prev.splitter_out[splitterOut].connected_component = null;
                    return prev;
                });
            })
        );
    };

    return (
        splitterDetail && (
            <Container fluid>
                <Table striped bordered hover className='mt-3'>
                    <tbody>
                        <tr>
                            <td>Splitter Id</td>
                            <td>{splitterDetail.id}</td>
                        </tr>
                        <tr>
                            <td>Name</td>
                            <td>{splitterDetail.name}</td>
                        </tr>
                        <tr>
                            <td>Parent Component/Fiber</td>
                            <td>
                                {}
                                {splitterDetail.fiber ? (
                                    <>
                                        <MdCable />
                                        {`${splitterDetail.fiber.cable.name} (${
                                            splitterDetail.fiber.fiber_number
                                        }: ${getColor(
                                            splitterDetail.fiber.fiber_number
                                        )})`}
                                    </>
                                ) : splitterDetail.connected_component ? (
                                    <ParentComponent
                                        connected_component={
                                            splitterDetail.connected_component
                                        }
                                    />
                                ) : (
                                    'None'
                                )}

                                {(splitterDetail.fiber ||
                                    splitterDetail.connected_component) && (
                                    <Badge
                                        pill
                                        className='ms-1'
                                        bg='danger'
                                        role='button'
                                        onClick={onParentDisconnectHandler}
                                    >
                                        <VscDebugDisconnect />
                                    </Badge>
                                )}
                            </td>
                        </tr>
                        <tr>
                            <td>Split Ratio</td>
                            <td>1:{splitterDetail.split_ratio}</td>
                        </tr>
                        <tr>
                            <td>Remarks</td>
                            <td>{splitterDetail.remarks}</td>
                        </tr>
                    </tbody>
                </Table>
                <ButtonGroup className='mb-1 btn-group-sm'>
                    <UpdateSplitterInfo
                        splitterDetail={splitterDetail}
                        setSpitterDetail={setSpitterDetail}
                    />
                    <Button variant='danger' onClick={onDeleteHandler}>
                        Delete
                    </Button>
                </ButtonGroup>
                <hr />
                <Row className='g-2'>
                    {splitterDetail.splitter_out.map((outputCore) => (
                        <SplitterOutputFiber
                            outputCore={outputCore}
                            key={outputCore.id}
                            onDisconnectSplitterOutput={
                                onDisconnectSplitterOutput
                            }
                        />
                    ))}
                </Row>
            </Container>
        )
    );
};

export default SplitterDetail;
