import { useEffect, useState } from "react";
import {
    Button,
    ButtonGroup,
    Container,
    Form,
    Modal,
    Row,
    Table,
} from "react-bootstrap";
import DevicePortDetail from "./DevicePortDetail";
import { toast } from "react-hot-toast";
import axiosInstance from "../../../../../../util/axiosInstance";
import { useDispatch } from "react-redux";
import {
    deleteDeviceFromCluster,
    disconnectDevicePort,
    updateDeviceInfo,
} from "../../../../../../store/asyncMethods/deviceMethod";

function UpdateInfo({ deviceDetail, setDeviceDetail }) {
    const dispatch = useDispatch();
    const oldDeviceInfo = {
        name: deviceDetail.name,
        manufactures: deviceDetail.manufactures,
        model: deviceDetail.model,
        serial_number: deviceDetail.serial_number,
    };
    const [newDeviceInfo, setDeviceInfo] = useState(oldDeviceInfo);

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

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

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

    const onSubmitHandler = async (e) => {
        e.preventDefault();
        dispatch(
            updateDeviceInfo(
                deviceDetail.id,
                newDeviceInfo,
                (deviceNewInfo) => {
                    setShow(false);
                    setDeviceDetail((prevState) => {
                        return {
                            ...prevState,
                            name: deviceNewInfo.name,
                            manufactures: deviceNewInfo.manufactures,
                            model: deviceNewInfo.model,
                            serial_number: deviceNewInfo.serial_number,
                        };
                    });
                }
            )
        );
    };

    return (
        <>
            <Button variant="warning" onClick={handleShow}>
                Update
            </Button>
            <Modal show={show} onHide={handleClose}>
                <Form onSubmit={onSubmitHandler}>
                    <Modal.Header closeButton>
                        <Modal.Title>Update Device Info</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <Form.Control
                            placeholder="Name"
                            className="mt-2"
                            name="name"
                            onChange={onChangeHandler}
                            value={newDeviceInfo.name}
                        />
                        <Form.Control
                            placeholder="Manufactures"
                            className="mt-2"
                            name="manufactures"
                            onChange={onChangeHandler}
                            value={newDeviceInfo.manufactures}
                        />
                        <Form.Control
                            placeholder="Model"
                            className="mt-2"
                            name="model"
                            onChange={onChangeHandler}
                            value={newDeviceInfo.model}
                        />
                        <Form.Control
                            placeholder="Serial Number"
                            className="mt-2"
                            name="serial_number"
                            onChange={onChangeHandler}
                            value={newDeviceInfo.serial_number}
                        />
                    </Modal.Body>
                    <Modal.Footer>
                        <Button variant="secondary" onClick={handleClose}>
                            Close
                        </Button>
                        <Button variant="primary" type="submit">
                            Save Changes
                        </Button>
                    </Modal.Footer>
                </Form>
            </Modal>
        </>
    );
}

const DeviceDetail = ({ selectedDevice, cluster }) => {
    const dispatch = useDispatch();
    const [deviceDetail, setDeviceDetail] = useState(null);

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

        const fetchDeviceDetail = async () => {
            try {
                const { data } = await axiosInstance.get(
                    `/devices/${selectedDevice.id}/detail`
                );
                setDeviceDetail(data);
            } catch (error) {
                toast.error(error.message);
            }
        };
        fetchDeviceDetail();
    }, [selectedDevice]);

    const onDeleteHandler = () => {
        if (!window.confirm("Are you sure you want to delete this device?"))
            return;
        dispatch(
            deleteDeviceFromCluster(deviceDetail.id, () => {
                setDeviceDetail(null);
            })
        );
    };

    const onPortDisconnect = async (portId) => {
        if (!window.confirm("Are you sure you want to disconnect this port?"))
            return;

        dispatch(
            disconnectDevicePort(portId, () => {
                setDeviceDetail((prevState) => {
                    const ports = prevState.ports;
                    const portIndex = ports.findIndex(
                        (port) => port.id === portId
                    );
                    ports[portIndex] = {
                        ...ports[portIndex],
                        connected_component_type: null,
                        connected_component_id: null,
                        fiber: null,
                        cable_id: null,
                        fiber_id: null,
                        connected_component: null,
                    };
                    return { ...prevState, ports };
                });
            })
        );
    };

    return (
        deviceDetail && (
            <Container fluid>
                <Table striped bordered hover className="mt-3">
                    <tbody>
                        <tr>
                            <td>Device Id</td>
                            <td>{deviceDetail.id}</td>
                        </tr>
                        <tr>
                            <td>Name</td>
                            <td>{deviceDetail.name}</td>
                        </tr>
                        <tr>
                            <td>manufactures</td>
                            <td>{deviceDetail.manufactures}</td>
                        </tr>
                        <tr>
                            <td>Device Model</td>
                            <td>{deviceDetail.model}</td>
                        </tr>
                        <tr>
                            <td>Serial Number</td>
                            <td>{deviceDetail.serial_number}</td>
                        </tr>
                        <tr>
                            <td>Device Total Ports</td>
                            <td>{deviceDetail.total_ports}</td>
                        </tr>
                        <tr>
                            <td>Remarks</td>
                            <td>{deviceDetail.remarks}</td>
                        </tr>
                    </tbody>
                </Table>
                <ButtonGroup className="mb-1 btn-group-sm">
                    <UpdateInfo
                        deviceDetail={deviceDetail}
                        setDeviceDetail={setDeviceDetail}
                    />
                    <Button variant="danger" onClick={onDeleteHandler}>
                        Delete
                    </Button>
                </ButtonGroup>
                <hr className="m-2" />
                <Row className="g-2">
                    {deviceDetail.ports.map((port) => (
                        <DevicePortDetail
                            key={port.id}
                            port={port}
                            cluster={cluster}
                            onPortDisconnect={onPortDisconnect}
                            setDeviceDetail={setDeviceDetail}
                        />
                    ))}
                </Row>
            </Container>
        )
    );
};

export default DeviceDetail;
