import Joi from "joi";
import React from "react";
import { Navigate } from "react-router-dom";
import { toast } from "react-toastify";
import Form, { FormState } from "../../../../components/common/Form";
import { InputType } from "../../../../components/common/Input";
import { GeneralIdRef, MakeGeneralIdRef } from "../../../../utils/GeneralIdRef";
import withRouter, { RouterProps } from "../../../../utils/withRouter";
import authentication from "../../../frame/services/authenticationService";
import userService from "../services/usersService";
import Loading from "../../../../components/common/Loading";
import { CustomFieldValue } from "../../glossary/services/glossaryService";

interface GeneralTabProps extends RouterProps {
    isEditMode: boolean;
}

interface GeneralTabState extends FormState {
    data: {
        firstName: string;
        lastName: string;
        middleNames: string;
        email: string;
        domain: CustomFieldValue[];
    };
    redirect: string;
}

class LocGeneralTab extends Form<GeneralTabProps, any, GeneralTabState> {
    state: GeneralTabState = {
        loaded: false,
        data: {
            firstName: "",
            lastName: "",
            middleNames: "",
            email: "",
            domain: [],
        },
        errors: {},
        redirect: "",
    };

    labelFirstName = "First name";
    labelMiddleNames = "Middle names";
    labelLastName = "Last name";
    labelEmail = "Mail";
    labelDomain = "Domain";

    labelApply = "Save";
    labelSave = "Save and close";

    schema = {
        firstName: Joi.string().required().max(450).label(this.labelFirstName),
        middleNames: Joi.string().allow("").required().label(this.labelMiddleNames),
        lastName: Joi.string().required().label(this.labelLastName),
        email: Joi.string()
            .required()
            .email({ tlds: { allow: false } })
            .label(this.labelEmail),
        domain: Joi.optional(),
    };

    doSubmit = async (buttonName: string) => {
        try {
            const { isEditMode } = this.props;

            const { firstName, middleNames, lastName, email, domain } = this.state.data;

            if (isEditMode) {
                const { userId } = this.props.router.params;

                var generalIdRef = MakeGeneralIdRef(userId);
                const response = await userService.putUser(generalIdRef, firstName, middleNames, lastName, email, domain[0]?.value as GeneralIdRef);
                if (response) {
                    toast.info("User edited");
                }
            } else {
                const response = await userService.postUser(firstName, middleNames, lastName, email, domain[0]?.value as GeneralIdRef);
                if (response) {
                    toast.info("New User added");
                }
            }

            if (buttonName === this.labelSave) this.setState({ redirect: "/users" });
        } catch (ex: any) {
            this.handleGeneralError(ex);
        }
    };

    componentDidMount = async () => {
        const { userId } = this.props.router.params;

        const { data } = this.state;

        if (userId !== undefined) {
            try {
                const loadedData = await userService.getUser(userId);
                if (loadedData) {
                    data.firstName = loadedData.firstName;
                    data.lastName = loadedData.lastName;
                    data.middleNames = loadedData.middleNames;
                    data.email = loadedData.email;
                    data.domain = [{ value: loadedData.domain }];
                }
            } catch (ex: any) {
                this.handleGeneralError(ex);
            }
        } else {
            const user = authentication.getCurrentUser();

            data.domain = [{ value: MakeGeneralIdRef(user?.domainid) }];
        }

        this.setState({ loaded: true, data });
    };

    render() {
        const { loaded, redirect } = this.state;
        if (redirect !== "") return <Navigate to={redirect} />;

        const { isEditMode } = this.props;
        return (
            <Loading loaded={loaded}>
                <form onSubmit={this.handleSubmit}>
                    {this.renderError("_general")}
                    {isEditMode && this.renderInput("email", this.labelEmail, InputType.text, true)}
                    {!isEditMode && this.renderInput("email", this.labelEmail)}
                    {this.renderInput("firstName", this.labelFirstName)}
                    {this.renderInput("middleNames", this.labelMiddleNames)}
                    {this.renderInput("lastName", this.labelLastName)}

                    {this.renderDomainPicker(true, "domain", this.labelDomain, 1, 1)}

                    {isEditMode && this.renderButton(this.labelApply)}
                    {this.renderButton(this.labelSave)}
                </form>
            </Loading>
        );
    }
}

const GeneralTab = withRouter(LocGeneralTab);

export default GeneralTab;
