import { useEffect, useMemo } from "react";
import "../../../resources/styles/home.scss"
import { IDeviceDto, IPropDto } from "../types";
import { DeviceCardStore } from "../model/DeviceCardStore";
import { Button, Center, IconButton, Skeleton, Spacer, useInterval } from "@chakra-ui/react";
import { observer } from "mobx-react";
import { MdOutlineDelete, MdOutlineSettings } from "react-icons/md";
import { homePageStore } from "../model/HomePageStore";




export const DeviceCard = observer((props: { data: IDeviceDto }) => {

    const deviceCardStore = useMemo(() => new DeviceCardStore(props.data.id), [props.data.id]);

    useInterval(() => { deviceCardStore.loadDeviceMeasurements() }, 5000);
    useEffect(() => { deviceCardStore.loadDeviceMeasurements() }, [deviceCardStore, props.data])

    const getPropsList = (props: IPropDto[], isLoading: boolean) => {
        return props.map(x =>
            <li key={x.id}>
                <h2>
                    {x.name}:
                </h2>
                {isLoading ?
                    <Center><Skeleton height={69} width={200} /></Center>
                    :
                    <p>
                        {deviceCardStore.deviceMeasurments![x.id.toString()]}{x.measureName}
                    </p>}
            </li>
        )
    }

    return (<>
        <div className="device_card_wrapper">
            <div className="device_card">
                <div className="h1_container">
                    <h1>{props.data.name}</h1>
                    <div className="button_container">
                        <IconButton
                            colorScheme="red"
                            onClick={() => homePageStore.deleteDevice(props.data.id)}
                            icon={<MdOutlineDelete />}
                            aria-label={"delete"}
                            fontSize={"90%"}
                            size={'sm'} />
                        <IconButton
                            onClick={() => homePageStore.setEditModalOpened(props.data.id, true)}
                            icon={<MdOutlineSettings />}
                            aria-label={"edit"}
                            fontSize={"90%"}
                            size={'sm'} />
                    </div>
                </div>
                <p style={{ textAlign: 'center' }}>{props.data.description}</p>
                <ul>
                    {getPropsList(props.data.props ?? [], deviceCardStore.isLoading)}
                </ul>
            </div>
        </div>
    </>);
});