// material-ui
import {
    Grid, Typography, Button,
    CircularProgress,
    // Dialog, DialogTitle, DialogContent, DialogActions,
} from '@mui/material';
import MainCard from "components/MainCard";
import * as React from "react";

import * as FieldUtils from "utils/FieldUtils";
import * as HttpUtils from 'utils/HttpUtils';
import * as UrlUtils from "utils/ApiPathConst";

import { useFormik } from 'formik';
import * as yup from 'yup';
const LoadingComponent = Loadable(lazy(() => import('../../extra-pages/LoadingComponent')));
import Loadable from 'components/Loadable';
import { lazy } from 'react';
import { notifySaveSuccess, } from 'utils/CommonFunction';
import {FormattedMessage, useIntl} from "react-intl";
import {PNSPS_BUTTON_THEME} from "../../../themes/buttonConst";
import {ThemeProvider} from "@emotion/react";
import * as ComboData from "utils/ComboData";

// import {
//     isPrimaryLoggedIn,
// } from "utils/Utils";
// ==============================|| DASHBOARD - DEFAULT ||============================== //


const UserInformationCard_Organization_Pub = ({ userData, loadDataFun,}) => {
    
    const intl = useIntl();
    const [currentUserData, setCurrentUserData] = React.useState(userData);
    // const [isWarningPopUp, setIsWarningPopUp] = React.useState(false);
    // const [warningText, setWarningText] = React.useState("");
    // const [isConfirmPopUp, setIsConfirmPopUp] = React.useState(false);
    // const [confirmText, setConfirmText] = React.useState("");
    // const [confirmAction, setConfirmAction] = React.useState();
    const [editMode, setEditMode] = React.useState(false);
    const [onReady, setOnReady] = React.useState(false);

    React.useEffect(() => {
        //if state data are ready and assign to different field
        // console.log(currentApplicationDetailData)
        if (Object.keys(currentUserData).length > 0) {
            setOnReady(true);
            // console.log(currentUserData)
        }
    }, [currentUserData]);

    function displayErrorMsg(errorMsg) {
        return <Typography variant="errorMessage1">{errorMsg}</Typography>
    }

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: currentUserData,
        validationSchema: yup.object().shape({
            tel_countryCode: yup.string().min(3, displayErrorMsg(intl.formatMessage({id: 'require3Number'}))).required(displayErrorMsg(intl.formatMessage({id: 'requireDialingCode'}))),
            phoneNumber: yup.string().min(8, displayErrorMsg(intl.formatMessage({id: 'require8Number'}))).required(displayErrorMsg(intl.formatMessage({id: 'requireContactNumber'}))),
        }),
        onSubmit: (values) => {
            return new Promise((resolve, reject) => {
                HttpUtils.post({
                    url: UrlUtils.POST_PUB_ORG_USER,
                    params: {
                        contactTel: {
                            countryCode: values.tel_countryCode,
                            phoneNumber: values.phoneNumber
                        },
                        faxNo: {
                            countryCode: values.fax_countryCode,
                            faxNumber: values.faxNumber
                        },
                        preferLocale: values.preferLocale.type
                    },
                    onSuccess: function () {
                        notifySaveSuccess();
                        loadDataFun();
                        resolve();
                    },
                    onFail: () => reject(),
                    onError: () => reject(),
                });
            });
        }

    });


    React.useEffect(() => {
        if (Object.keys(userData).length > 0) {
            setCurrentUserData(userData);
        }
    }, [userData]);

    const onEditClick = () => {
        setEditMode(true);
    };

    const onResetBack = async () => {
        setEditMode(false);
        loadDataFun();          // reload userData + orgData
        formik.resetForm();     // reset to latest initialValues after reinitialize
    };

    // const onFocus = () => {
    //     loadDataFun();
    //     window.removeEventListener("focus", onFocus)
    // }

    return (
        <MainCard elevation={0}
            border={false}
            content={false}
        >

            {!onReady ?
                <LoadingComponent />
                :
                <form onSubmit={formik.handleSubmit}>

                    {/*top button*/}
                    <Grid container alignItems="center" justifyContent="flex-start">
                        <Grid item s={12} md={12} lg={12} sx={{ mb: 3, mt: 2 }}>
                            <Grid container direction="row" justifyContent="flex-start">
                                {editMode ?
                                    <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                        <Grid item xs={4} sx={{ ml: 3, mr: 3 }}>
                                            <Button
                                                variant="contained"
                                                onClick={onResetBack}
                                                color="cancel"
                                                disabled={formik.isSubmitting}
                                            >
                                                <FormattedMessage id="resetAndBack" />

                                            </Button>
                                        </Grid>
                                        <Grid item xs={4} sx={{ ml: 3, mr: 3 }}>
                                            <Button
                                                variant="contained"
                                                type="submit"
                                                color="success"
                                                disabled={formik.isSubmitting}
                                                startIcon={formik.isSubmitting ? <CircularProgress color="inherit" size={18} /> : null}
                                            >
                                                <FormattedMessage id="save" />

                                            </Button>
                                        </Grid>
                                    </ThemeProvider>
                                    :
                                    <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                        <Grid item sx={{ ml:3, mr: 3 }}>
                                            <Button
                                                variant="contained"
                                                onClick={onEditClick}
                                                color="success"
                                            >
                                                <FormattedMessage id="edit" />

                                            </Button>
                                        </Grid>
                                    </ThemeProvider>
                                }


                            </Grid>
                        </Grid>
                    </Grid>
                    {/*end top button*/}
                    <div style={{ paddingLeft: 24, paddingRight: 24 }}>
                        {/* <Typography variant="h4" sx={{ mt: 3, mb: 2, mr: 3, borderBottom: "1px solid black" }}>
                            <FormattedMessage id="userDetail" />
                        </Typography> */}
                        <Grid container spacing={1}>
                            <Grid item xs={12} lg={12}>
                                {FieldUtils.getTextField({
                                    label: intl.formatMessage({id: 'userLoginName'}) + ":",
                                    valueName: "username",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

                            <Grid item xs={12} lg={12}>
                                {FieldUtils.getTextField({
                                    label: intl.formatMessage({id: 'userContactName'}) + ":",
                                    valueName: "contactPerson",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

                            <Grid item xs={12} lg={12}>
                                {FieldUtils.getTextField({
                                    label: intl.formatMessage({id: 'userContactEmail'}) + ":",
                                    valueName: "emailBus",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

                            <Grid item xs={12} lg={12}>
                                {FieldUtils.getPhoneField({
                                    label: intl.formatMessage({id: 'userContactNumber'}) + ":",
                                    valueName: {
                                        code: "tel_countryCode",
                                        num: "phoneNumber"
                                    },
                                    disabled: (!editMode),
                                    form: formik
                                })}
                            </Grid>

                            <Grid item xs={12} lg={12}>
                                {FieldUtils.getPhoneField({
                                    label: intl.formatMessage({id: 'contactFaxNumber'}) + ":",
                                    valueName: {
                                        code: "fax_countryCode",
                                        num: "faxNumber"
                                    },
                                    disabled: (!editMode),
                                    form: formik
                                })}
                            </Grid>

                            <Grid item xs={12} lg={12}>
                                {FieldUtils.getTextField({
                                    label: intl.formatMessage({id: 'primaryUser'}) + ":",
                                    valueName: "primaryUser",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>
                            <Grid item xs={12} lg={12}>
                                {FieldUtils.getComboField({
                                    label: intl.formatMessage({id: 'language'}) + ":",
                                    valueName: "preferLocale",
                                    dataList: ComboData.Locale,
                                    getOptionLabel: (option) => (option?.label != null ? String(option.label) : ""),
                                    disabled: (!editMode),
                                    form: formik
                                })}
                            </Grid>

                        </Grid>
                    </div>
                    <br />
                </form>
            }
            {/* <div>
                <Dialog open={isWarningPopUp} onClose={() => setIsWarningPopUp(false)}  >
                    <DialogTitle><Typography variant="h3">Warning</Typography></DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h4" style={{ padding: '16px' }}>{warningText}</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setIsWarningPopUp(false)}><Typography variant="h5">Close</Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
            <div>
                <Dialog open={isConfirmPopUp} onClose={() => setIsConfirmPopUp(false)}  >
                    <DialogTitle><Typography variant="h3">Confirm</Typography></DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h4" style={{ padding: '16px' }}>{confirmText}</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => { setIsConfirmPopUp(false) }}><Typography variant="h5">Close</Typography></Button>
                        <Button onClick={() => { confirmAction?.function(); }}><Typography variant="h5">Confirm</Typography></Button>
                    </DialogActions>
                </Dialog>
            </div> */}
        </MainCard>
    );
};

export default UserInformationCard_Organization_Pub;
