import { observer } from "mobx-react";
import { homePageStore } from "../../model/HomePageStore";
import { Button, Center, Input, Modal, ModalBody, ModalCloseButton, ModalContent, ModalHeader, ModalOverlay, Stack, Textarea } from "@chakra-ui/react";
import { IDeviceDto } from "../../types";
import { useEffect, useState } from "react";

export const EditModal = observer(() => {
    const currentDevice = homePageStore.currentEditDevice

    const [name, setName] = useState(currentDevice?.name);
    const [description, setDescription] = useState(currentDevice?.description);
    const [url, setUrl] = useState(currentDevice?.deviceUrl);

    useEffect(
        () => {
            setName(currentDevice?.name);
            setDescription(currentDevice?.description);
            setUrl(currentDevice?.deviceUrl)
        },
        [currentDevice]
    )

    const onUpdateDevice = () => {
        homePageStore.setEditModalOpened(currentDevice!.id, false);
        homePageStore.updateDevice({
            id: currentDevice?.id,
            name: name,
            description: description,
            deviceUrl: url
        } as IDeviceDto);
    }

    return (<Modal
        onClose={() => homePageStore.setEditModalOpened(homePageStore.editModalCurrentId!, false)}
        isOpen={homePageStore.isEditModalOpened}
        isCentered
        blockScrollOnMount={false}
    >
        <ModalOverlay />
        <ModalContent>
            <ModalHeader>Редактировать</ModalHeader>
            <ModalCloseButton />
            <ModalBody>
                <Stack spacing={3}>
                    <label>Название:</label>
                    <Input
                        value={name ?? ""}
                        onChange={e => setName(e.target.value)}
                        disabled={homePageStore.isLoading} />
                    <label>Описание:</label>
                    <Textarea
                        value={description ?? ""}
                        onChange={e => setDescription(e.target.value)}
                        disabled={homePageStore.isLoading} />
                    <label>URL:</label>
                    <Input
                        value={url ?? ""}
                        onChange={e => setUrl(e.target.value)}
                        disabled={homePageStore.isLoading} />
                </Stack>
                <Center>
                    <Button
                        colorScheme="green"
                        marginTop={10}
                        onClick={() => onUpdateDevice()}
                        isLoading={homePageStore.isLoading}>Сохранить</Button>
                </Center>
            </ModalBody>
        </ModalContent>
    </Modal>);
});