import {ComponentContext} from "../../utils/ComponentContext";
import {observer} from "mobx-react";
import {ModalState} from "../../utils/modalState";
import {action, computed, makeObservable, observable} from "mobx";
import {ReactiveValue} from "../../utils/reactive/reactiveValue";
import {required, strLength, strPattern} from "../../utils/reactive/validators";
import {Button, Modal, ModalBody, ModalFooter, ModalHeader, ModalTitle} from "react-bootstrap";
import {StringInput} from "../custom/controls/ReactiveControls";
import {post} from "../../utils/request";

export interface CreateGroupModalProps {
    modalState: ModalState;
}

@observer
export class AddGroupModal extends ComponentContext<CreateGroupModalProps> {
    constructor(props: any) {
        super(props);
        makeObservable(this);
    }

    @observable name = new ReactiveValue<string>()
        .addValidator(required)
        .addValidator(strLength(3, 50))
        .addInputRestriction(strPattern(/^[а-яА-ЯёЁ0-9_-]*$/, "Имя группы должно содержать только русские буквы, цифры и символы _-"));

    @action.bound
    creationRequest() {
        post<void>('/group/create-group', {name: this.name.value}, false).then(() => {
            this.notificationStore.success(`Группа ${this.name.value} создана`);
        }).finally(() => {
            this.props.modalState.close();
        });
    }

    @computed
    get formInvalid() {
        return this.name.invalid || !this.name.touched;
    }

    render() {
        return <Modal show={this.props.modalState.isOpen}>
            <ModalHeader>
                <ModalTitle>Добавление группы</ModalTitle>
            </ModalHeader>
            <ModalBody>
                <StringInput value={this.name} label={'Имя группы'}/>
            </ModalBody>
            <ModalFooter>
                <Button onClick={this.creationRequest} disabled={this.formInvalid}>Создать</Button>
                <Button onClick={this.props.modalState.close} variant={'secondary'}>Закрыть</Button>
            </ModalFooter>
        </Modal>
    }
}