// material-ui
import {
    Grid, Typography, Button,
    Dialog, DialogTitle, DialogContent, DialogActions,
    CircularProgress,
} from '@mui/material';
import MainCard from "components/MainCard";
import { useState, useEffect, lazy } from 'react';
import * as FieldUtils from "utils/FieldUtils";
import * as HttpUtils from 'utils/HttpUtils';
import { POST_ORG_USER, GET_IND_USER_VERIFY, GET_USER_LOCK, GET_USER_UNLOCK } from "utils/ApiPathConst";
import * as ComboData from "utils/ComboData";

import { useFormik } from 'formik';
import * as yup from 'yup';
const LoadingComponent = Loadable(lazy(() => import('pages/extra-pages/LoadingComponent')));
import Loadable from 'components/Loadable';
import { notifyActiveSuccess, notifyLockSuccess, notifySaveSuccess, notifyVerifySuccess } from 'utils/CommonFunction';
import { useIntl } from "react-intl";
import { PNSPS_BUTTON_THEME } from "themes/buttonConst";
import { ThemeProvider } from "@emotion/react";
import { isGrantedAny } from "auth/utils";
// ==============================|| DASHBOARD - DEFAULT ||============================== //


const UserInformationCard_Organization = ({ userData, loadDataFun, orgData }) => {

    const [currentUserData, setCurrentUserData] = useState(userData);
    const [isWarningPopUp, setIsWarningPopUp] = useState(false);
    const [warningText, setWarningText] = useState("");
    const [isConfirmPopUp, setIsConfirmPopUp] = useState(false);
    const [confirmText, setConfirmText] = useState("");
    const [confirmAction, setConfirmAction] = useState();
    const [editMode, setEditMode] = useState(false);
    const [onReady, setOnReady] = useState(false);
    const intl = useIntl();
    useEffect(() => {
        //if state data are ready and assign to different field
        // console.log(currentApplicationDetailData)
        if (Object.keys(currentUserData).length > 0) {
            setOnReady(true);
        }
    }, [currentUserData]);

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

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: currentUserData,
        validationSchema: yup.object().shape({
            contactPerson: yup.string().max(255).required(displayErrorMsg(intl.formatMessage({ id: 'userRequireName' }))),
            enCompanyName: yup.string().max(255).required(displayErrorMsg(intl.formatMessage({ id: 'userRequireEnglishName' }))),
            chCompanyName: yup.string().max(255).nullable(),
            addressLine1: yup.string().max(40).required(displayErrorMsg(intl.formatMessage({ id: 'validateAddressLine1' }))),
            addressLine2: yup.string().max(40).nullable(),
            addressLine3: yup.string().max(40).nullable(),
            emailBus: yup.string().max(255).required(displayErrorMsg(intl.formatMessage({ id: 'requireEmail' }))),
            tel_countryCode: yup.string().min(3, displayErrorMsg(intl.formatMessage({ id: 'require3Number' }))).required(displayErrorMsg(intl.formatMessage({ id: 'requireDialingCode' }))),
            fax_countryCode: yup.string().min(3, displayErrorMsg(intl.formatMessage({ id: 'require3Number' }))).nullable(),
            phoneNumber: yup.string().min(8, displayErrorMsg(intl.formatMessage({ id: 'require8Number' }))).required(displayErrorMsg(intl.formatMessage({ id: 'requireContactNumber' }))),
            faxNumber: yup.string().min(8, displayErrorMsg(intl.formatMessage({ id: 'require8Number' }))).nullable(),
            brExpiryDate: yup.string().min(8, displayErrorMsg(intl.formatMessage({ id: 'pleaseFillInBusinessRegCertValidityDate' }))),
            brNo: yup.string().max(8).required(displayErrorMsg(intl.formatMessage({ id: 'pleaseFillInBusinessRegCertNumber' })))
                .test('checkBrNoFormat', displayErrorMsg(`${intl.formatMessage({ id: 'pleaseFillInValidBusinessRegCertNumber' })} (e.g. 12341234)`), function (value) {
                    var brNo_pattern = /[0-9]{8}/
                    if (value !== undefined) {
                        if (value.match(brNo_pattern)) {
                            return true
                        } else {
                            return false
                        }
                    }
                }),
        }),
        onSubmit: (values) => {
            return new Promise((resolve, reject) => {
                HttpUtils.post({
                    url: POST_ORG_USER + "/" + userData.id,
                    params: {
                        contactTel: {
                            countryCode: values.tel_countryCode,
                            phoneNumber: values.phoneNumber
                        },
                        faxNo: {
                            countryCode: values.fax_countryCode,
                            faxNumber: values.faxNumber
                        },
                        emailBus: values.emailBus,
                        contactPerson: values.contactPerson,
                        orgId: values.orgId?.id,
                        preferLocale: values.preferLocale?.type
                    },
                    onSuccess: function () {
                        notifySaveSuccess();
                        loadDataFun();
                        resolve();
                    },
                    onFail: () => reject(),
                    onError: () => reject(),
                });
            });
        }

    });


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

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

    const createOrgClick = () => {
        window.open("/org/fromUser/" + userData.id, "_blank", "noreferrer");
        window.addEventListener("focus", onFocus)
    };

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

    const onVerifiedClick = () => {
        if (formik?.values?.orgId) {
            HttpUtils.get({
                url: GET_IND_USER_VERIFY + "/" + userData.id,
                onSuccess: function () {
                    notifyVerifySuccess()
                    loadDataFun();
                }
            });
        } else {
            setWarningText("Please select Organisation before active this account.")
            setIsWarningPopUp(true);
        }

    };

    const doLock = () => {
        setConfirmText("Confirm to Lock this Account?");
        setConfirmAction({
            function: function () {
                HttpUtils.get({
                    url: GET_USER_LOCK + "/" + userData.id,
                    onSuccess: function () {
                        notifyLockSuccess()
                        loadDataFun();
                    }
                });
            }
        });
        setIsConfirmPopUp(true);
    };

    const doUnlock = () => {
        setConfirmText("Confirm to Un-Lock this Account?");

        setConfirmAction({
            function: function () {
                HttpUtils.get({
                    url: GET_USER_UNLOCK + "/" + userData.id,
                    onSuccess: function () {
                        notifyActiveSuccess()
                        loadDataFun();
                    }
                });
            }
        });
        setIsConfirmPopUp(true);
    };

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

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

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

                    {/*top button*/}

                    {isGrantedAny(["MAINTAIN_USER", "MAINTAIN_ORG_USER"]) ?
                        <Grid item s={12} md={12} lg={12} sx={{ mb: 3, mt: 2 }} alignItems={"start"} justifyContent="center">
                            <Grid container maxWidth justifyContent="flex-start">
                                {editMode ?
                                    <>
                                        <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                            <Grid item sx={{ ml: 3, mr: 3 }}>
                                                <Button
                                                    variant="contained"
                                                    onClick={onResetBack}
                                                    color="cancel"
                                                    disabled={formik.isSubmitting}
                                                >
                                                    Reset & Back
                                                </Button>
                                            </Grid>
                                            <Grid item sx={{ ml: 3, mr: 3 }}>
                                                <Button
                                                    variant="contained"
                                                    type="submit"
                                                    color="success"
                                                    disabled={formik.isSubmitting}
                                                    startIcon={formik.isSubmitting ? <CircularProgress color="inherit" size={18} /> : null}
                                                >
                                                    Save
                                                </Button>
                                            </Grid>
                                        </ThemeProvider>
                                    </>
                                    :
                                    <>

                                        <Grid item sx={{ ml: 3, mr: 3 }}>
                                            <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                                <Button
                                                    variant="contained"
                                                    onClick={onEditClick}
                                                    color="success"
                                                >
                                                    Edit
                                                </Button>
                                            </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" }}>
                            Organisation User Details
                        </Typography>
                        <Grid container spacing={1}>
                            <Grid item lg={4}>
                                {FieldUtils.getTextField({
                                    label: "Username:",
                                    valueName: "username",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={4}>
                                {FieldUtils.getTextField({
                                    label: "Name:",
                                    valueName: "contactPerson",
                                    disabled: (!editMode),
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={4}>
                                {FieldUtils.getTextField({
                                    label: "Created Date:",
                                    valueName: "createDate",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={4}>
                                {FieldUtils.getTextField({
                                    label: "Email:",
                                    valueName: "emailBus",
                                    disabled: (!editMode),
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={4}>
                                {FieldUtils.getPhoneField({
                                    label: "Contact Tel:",
                                    valueName: {
                                        code: "tel_countryCode",
                                        num: "phoneNumber"
                                    },
                                    disabled: (!editMode),
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={4}>
                                {FieldUtils.getTextField({
                                    label: "Last Updated:",
                                    valueName: "modifieDate",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={4}>
                                {FieldUtils.getComboField({
                                    label: "Organisation:",
                                    valueName: "orgId",
                                    getOptionLabel: (option) => option.enCompanyName ? option.enCompanyName : option.chCompanyName ? option.chCompanyName : "",
                                    dataList: orgData,
                                    disabled: (!editMode),
                                    form: formik
                                })}
                                {/* {FieldUtils.getComboField({
                                    label: "Organisation:",
                                    valueName: "orgId",
                                    disabled: (!editMode),
                                    dataList: orgData,
                                    filterOptions: (options, state) => {
                                        if (!state || !state.inputValue) return options;
                                        let searchStr = state.inputValue.toLowerCase().toLowerCase().trim();
                                        const displayOptions = options.filter((option) => {
                                            let brNo = option.brNo.toLowerCase().trim();
                                            let enCompanyName = option.enCompanyName ? option.enCompanyName.toLowerCase().trim() : "";
                                            let chCompanyName = option.chCompanyName ? option.chCompanyName.toLowerCase().trim() : "";
                                            return brNo.includes(searchStr) || enCompanyName.includes(searchStr) || chCompanyName.includes(searchStr);
                                        },
                                        );
                                        return displayOptions;
                                    },
                                    getOptionLabel: (item) => item ? typeof item === 'number' ? item + "" : (item["brNo"] ?
                                        <div>BR No.: {item["brNo"]}<div>Org. Name(Eng): {item["enCompanyName"] === null ? "N/A" : item["enCompanyName"]}</div><div>Org. Name(CH): {item["chCompanyName"] === null ? "N/A" : item["chCompanyName"]}</div></div> : "")
                                        : "",
                                    isOptionEqualToValue: (option, newValue, setValue, setInputValue) => {
                                        if (option.id == newValue || option.id == newValue.id) {
                                            setValue(option);
                                            setInputValue(option["brNo"]);
                                            return true;
                                        }
                                        return option == newValue || option.id == newValue.id;
                                    },
                                    onInputChange: (event, newValue, setInputValue) => {
                                        if (newValue !== "[object Object]") {
                                            setInputValue(newValue);
                                        }
                                    },
                                    onChange: (event, newValue) => {
                                        if (newValue == null) {
                                            formik.setFieldValue("orgId", "");
                                            return;
                                        }
                                        formik.setFieldValue("orgId", newValue.id);
                                    },
                                    form: formik
                                })} */}
                            </Grid>

                            <Grid item xs={12} sm={12} md={12} lg={4}>
                                {FieldUtils.getPhoneField({
                                    label: "Fax No.:",
                                    valueName: {
                                        code: "fax_countryCode",
                                        num: "faxNumber"
                                    },
                                    disabled: (!editMode),
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={4}>
                                {FieldUtils.getTextField({
                                    label: "Last Login:",
                                    valueName: "lastLoginDate",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>
                            <Grid item xs={12} sm={12} md={12} lg={4}>
                                {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 item lg={4}>
                                <Grid container alignItems={"center"}>
                                    <Grid item xs={12} md={3} lg={3} sx={{ display: 'flex', alignItems: 'center' }}>
                                        <Typography variant="h5">Verified:</Typography>
                                    </Grid>

                                    {
                                         !isGrantedAny(["MAINTAIN_USER", "MAINTAIN_ORG_USER"]) || currentUserData.verifiedBy || editMode ?
                                            <Grid item xs={12} md={6} lg={6}>
                                                {FieldUtils.initField({
                                                    valueName: "verifiedStatus",
                                                    disabled: true,
                                                    form: formik,
                                                })}
                                            </Grid>
                                            :
                                            <>
                                                <Grid item xs={10} md={4} lg={4}>
                                                    {FieldUtils.initField({
                                                        valueName: "verifiedStatus",
                                                        disabled: true,
                                                        form: formik,
                                                    })}
                                                </Grid>
                                                
                                                <Grid item xs={1} md={1} lg={1}>
                                                    <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                                        <Button
                                                            variant="contained"
                                                            onClick={() => { onVerifiedClick() }}
                                                        >
                                                            Verify
                                                        </Button>
                                                    </ThemeProvider>
                                                </Grid>
                                            </>
                                    }

                                </Grid>
                            </Grid>

                            <Grid item lg={4}>
                                <Grid container alignItems={"center"}>
                                    <Grid item xs={12} md={3} lg={3} sx={{ display: 'flex', alignItems: 'center' }}>
                                        <Typography variant="h5">Status:</Typography>
                                    </Grid>
                                    {
                                        !isGrantedAny(["MAINTAIN_USER", "MAINTAIN_ORG_USER"]) || editMode ?
                                            <Grid item xs={12} md={6} lg={6}>
                                                {FieldUtils.initField({
                                                    valueName: "status",
                                                    disabled: true,
                                                    form: formik,
                                                })}
                                            </Grid>
                                            :
                                            <>

                                                <Grid item xs={10} md={4} lg={4}>
                                                    {FieldUtils.initField({
                                                        valueName: "status",
                                                        disabled: true,
                                                        form: formik,
                                                    })}
                                                </Grid>

                                                {formik.values.locked ?
                                                    <Grid item xs={1} md={1} lg={1} sx={{ ml: 1 }}>
                                                        <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                                            <Button
                                                                variant="contained"
                                                                color="success"
                                                                onClick={doUnlock}
                                                            >
                                                                Active
                                                            </Button>
                                                        </ThemeProvider>
                                                    </Grid>
                                                    :
                                                    <Grid item xs={1} md={1} lg={1} sx={{ ml: 1 }}>
                                                        <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                                            <Button
                                                                variant="contained"
                                                                color="error"
                                                                onClick={doLock}
                                                            >
                                                                Lock
                                                            </Button>
                                                        </ThemeProvider>
                                                    </Grid>
                                                }
                                            </>
                                    }
                                </Grid>
                            </Grid>
                        </Grid>
                    </div>
                    <br />
                    <div style={{ paddingLeft: 24, paddingRight: 24 }}>
                        <Grid container spacing={1} >
                            <Grid item lg={12}>
                                <Grid container alignItems={"center"}>
                                    {currentUserData.orgId == null ?
                                        isGrantedAny("MAINTAIN_ORG")?
                                            <Grid item lg={2} >
                                                <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                                    <Button variant="contained"
                                                        onClick={createOrgClick}
                                                    >
                                                        Create Organisation
                                                    </Button>
                                                </ThemeProvider>
                                            </Grid>
                                        : null
                                    : null
                                    }
                                </Grid>
                            </Grid>
                            <Grid item lg={12} >
                                <Typography variant="h4" sx={{ mt: 3, mb: 2, mr: 3, borderBottom: "1px solid black" }}>
                                    Organisation
                                </Typography>
                            </Grid>
                            <Grid item lg={4}>
                                {FieldUtils.getTextField({
                                    label: "Org.Name (English):",
                                    valueName: "enCompanyName",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={4}>
                                {FieldUtils.getTextField({
                                    label: "Org.Name (Chinese):",
                                    valueName: "chCompanyName",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={4}>
                                {FieldUtils.getTextField({
                                    label: "BR No.:",
                                    valueName: "brNo",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={4}>
                                {FieldUtils.getComboField({
                                    label: "Country:",
                                    valueName: "country",
                                    getOptionLabel: (option) => option.type ? intl.formatMessage({ id: option.type }) : "",
                                    dataList: ComboData.country,
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={4}>
                                {FieldUtils.getPhoneField({
                                    label: "Contact Tel:",
                                    valueName: {
                                        code: "org_tel_countryCode",
                                        num: "orgPhoneNumber"
                                    },
                                    disabled: (!editMode),
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={4}>
                                {FieldUtils.getDateField({
                                    label: "BR Expiry Date.:",
                                    valueName: "brExpiryDate",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={4}>
                                {FieldUtils.getComboField({
                                    label: "District:",
                                    valueName: "district",
                                    dataList: ComboData.district,
                                    getOptionLabel: (option) => option.type ? intl.formatMessage({ id: option.type }) : "",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={4}>
                                {FieldUtils.getPhoneField({
                                    label: "Fax No.:",
                                    valueName: {
                                        code: "org_fax_countryCode",
                                        num: "orgFaxNumber"
                                    },
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

                            <Grid item lg={12}>
                                {FieldUtils.getAddressField({
                                    label: "Address:",
                                    valueName: ["addressLine1", "addressLine2", "addressLine3"],
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

                        </Grid>
                    </div>
                    <br />
                </form>
            }
            <div>
                <Dialog
                    open={isWarningPopUp}
                    onClose={() => setIsWarningPopUp(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogTitle><Typography variant="h3">Warning</Typography></DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h4" style={{ padding: '16px' }}>{warningText}</Typography>
                    </DialogContent>
                    <DialogActions>
                        <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                            <Button onClick={() => setIsWarningPopUp(false)}>
                                Close
                            </Button>
                        </ThemeProvider>
                    </DialogActions>
                </Dialog>
            </div>
            <div>
                <Dialog
                    open={isConfirmPopUp}
                    onClose={() => setIsConfirmPopUp(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogTitle><Typography variant="h3">Confirm</Typography></DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h4" style={{ padding: '16px' }}>{confirmText}</Typography>
                    </DialogContent>
                    <DialogActions>
                        <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                            <Button onClick={() => { setIsConfirmPopUp(false) }}>
                                Close
                            </Button>
                            <Button onClick={() => { confirmAction?.function(); }}>
                                Confirm
                            </Button>
                        </ThemeProvider>
                    </DialogActions>
                </Dialog>
            </div>
        </MainCard>
    );
};

export default UserInformationCard_Organization;
