// material-ui
import {
    Grid, Button, Typography,
    FormHelperText,
} from '@mui/material';
import MainCard from "components/MainCard";
import * as React from "react";
import { useEffect, useState } from "react";
import * as yup from 'yup';

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


const UserInformationCard_Individual_Pub = ({ formData, loadDataFun }) => {

    const intl = useIntl();
    const [currentUserData, setCurrentUserData] = useState({});
    const [editMode, setEditMode] = useState(false);
    const [onReady, setOnReady] = useState(false);
    const [errorMsg, setErrorMsg] = useState("");

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

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

    
    function getMaxErrStr(num, fieldname){
        return intl.formatMessage({ id: 'noMoreThenNWords' },{num:num, fieldname:fieldname?intl.formatMessage({ id: fieldname})+": ":""});
    }

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: currentUserData,
        validationSchema: yup.object().shape({
            enName: yup.string().max(40, getMaxErrStr(40)).when('chName', {
                is: (chName) => chName?false:true,
                then: yup.string().required(intl.formatMessage({ id: 'userRequireEnglishName' }))
            }).nullable(),
            chName: yup.string().max(6, getMaxErrStr(6)).nullable(),
            addressLine1: yup.string().max(40).required(intl.formatMessage({id: 'validateAddressLine1'})),
            addressLine2: yup.string().max(40).nullable(),
            addressLine3: yup.string().max(40).nullable(),
            emailAddress: yup.string().email(intl.formatMessage({id: 'validEmailFormat'})).max(255).required(intl.formatMessage({id: 'requireEmail'})),
            tel_countryCode: yup.string().min(3, intl.formatMessage({id: 'require3Number'})).required(intl.formatMessage({id: 'requireDialingCode'})),
            fax_countryCode: yup.string().min(3, intl.formatMessage({id: 'require3Number'})),
            phoneNumber: yup.string().min(8, intl.formatMessage({id: 'require8Number'})).required(intl.formatMessage({id: 'requireContactNumber'})),
            faxNumber: yup.string().min(8, intl.formatMessage({id: 'require8Number'})).nullable(),
        }),
        onSubmit: (values, { setSubmitting }) => {
            if (values.country == null) {
                setErrorMsg(intl.formatMessage({ id: 'pleaseFillInCountry' }));
                return;
            }
            if (values.country.type === "hongKong" && values.district == null) {
                setErrorMsg(intl.formatMessage({ id: 'pleaseFillInDistrict' }));
                return;
            }
            return new Promise((resolve) => {
                HttpUtils.post({
                    url: UrlUtils.POST_PUB_IND_USER,
                    params: {
                        enName: values.enName,
                        chName: values.chName,
                        mobileNumber: {
                            countryCode: values.tel_countryCode,
                            phoneNumber: values.phoneNumber
                        },
                        faxNo: {
                            countryCode: values.fax_countryCode,
                            faxNumber: values.faxNumber
                        },
                        address: {
                            country: values.country.type,
                            district: values.district?.type,
                            addressLine1: values.addressLine1,
                            addressLine2: values.addressLine2,
                            addressLine3: values.addressLine3,
                        },
                        preferLocale: values.preferLocale.type
                    },
                    onSuccess: function () {
                        notifySaveSuccess();
                        resolve();
                        window.location.reload();
                    },
                    onFail: function () {
                        setSubmitting(false);
                        resolve();
                    },
                    onError: function () {
                        setSubmitting(false);
                        resolve();
                    }
                });
            });
        }
    });

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

    return (
        <MainCard elevation={0}
            border={false}
            content={false}
        >
            {!onReady ?
                <LoadingComponent />
                :
                <form onSubmit={formik.handleSubmit} style={{ padding: 12 }}>
                    {/*top button*/}
                    <Grid item xs={12} sm={12} md={12} lg={12} sx={{ mb: 3 }} alignItems={"start"} justifyContent="center">
                        <Grid container maxWidth justifyContent="flex-start">
                            {editMode ?
                                <>
                                <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                <Grid item sx={{ mr: 3 }}>
                                        <Button
                                            aria-label={intl.formatMessage({id: 'back'})}
                                            variant="contained"
                                            color="cancel"
                                            onClick={loadDataFun}
                                            disabled={formik.isSubmitting}
                                        >
                                            <FormattedMessage id="resetAndBack" />
                                        </Button>
                                    </Grid>

                                    <Grid item sx={{ ml: 3, mr: 3 }}>
                                        <Button
                                            aria-label={intl.formatMessage({id: 'save'})}
                                            variant="contained"
                                            type="submit"
                                            sx={PRIMARY_CONTAINED_BUTTON_SX}
                                            disabled={formik.isSubmitting}
                                        >
                                            <FormattedMessage id="save" />
                                        </Button>
                                    </Grid>
                                </ThemeProvider>
                                </>
                                :
                                <>
                                <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                <Grid item sx={{ mr: 3 }}>
                                        <Button
                                            aria-label={intl.formatMessage({id: 'edit'})}
                                            variant="contained"
                                            onClick={onEditClick}
                                        >
                                            <FormattedMessage id="edit" />
                                        </Button>
                                    </Grid>
                                </ThemeProvider>
                                </>
                            }
                        </Grid>
                    </Grid>
                    {/*end top button*/}
                    {/* <Typography variant="h4" sx={{ mt: 3, mb: 2, borderBottom: "1px solid black" }}>
                        <FormattedMessage id="userDetail" />
                    </Typography> */}
                    <Grid item xs={12} sm={12} md={12} lg={12}>
                        <Grid container>
                            <Grid item xs={12}>
                                <FormHelperText error id="helper-text-address1-signup">
                                    <Typography variant="errorMessage1">
                                        {errorMsg}
                                    </Typography>
                                </FormHelperText>
                            </Grid>
                            <Grid item xs={12} sm={12} md={12} lg={4} >
                                {FieldUtils.getTextField({
                                    label: intl.formatMessage({id: 'userLoginName'}) + ":",
                                    valueName: "username",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

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

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

                            <Grid item xs={12} sm={12} md={12} lg={4}>
                                {FieldUtils.getComboField({
                                    label: intl.formatMessage({id: 'idType'}) + ":",
                                    valueName: "idDocType",
                                    disabled: true,
                                    dataList: ComboData.idDocType,
                                    getOptionLabel: (option) => option? intl.formatMessage({ id: option }) : "",
                                    form: formik
                                })}
                            </Grid>

                            <Grid item xs={12} sm={12} md={12} lg={4}>
                                <Grid container alignItems={"center"} spacing={1} sx={{mb:2}} >
                                    <Grid item xs={12} sm={12} md={3} lg={3} sx={{ display: 'flex', alignItems: 'center' }}>
                                        <Typography variant="pnspsFormParagraphBold">
                                            <FormattedMessage id="idNo" />:
                                        </Typography>
                                    </Grid>

                                    <Grid item xs={12} sm={12} md={9} lg={6}>
                                        <Typography variant="h5" mt={1}>
                                            {formik.values.identification?.slice(0, 4)}
                                        </Typography>
                                    </Grid>
                                </Grid>
                            </Grid>

                            <Grid item xs={12} sm={12} md={12} lg={4}>
                                {FieldUtils.getPhoneField({
                                    label: intl.formatMessage({id: 'userContactNumber'}) + ":",
                                    valueName: {
                                        code: "tel_countryCode",
                                        num: "phoneNumber"
                                    },
                                    disabled: (!editMode),
                                    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 xs={12} sm={12} md={12} lg={4}>
                                {FieldUtils.getTextField({
                                    label: intl.formatMessage({id: 'userContactEmail'}) + ":",
                                    valueName: "emailAddress",
                                    disabled: true,
                                    form: formik
                                })}
                            </Grid>

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

                            <Grid item xs={12} sm={12} md={12} lg={12}>
                                {FieldUtils.getAddressField({
                                    label: intl.formatMessage({id: 'userAddress'}) + ":",
                                    valueName: ["addressLine1", "addressLine2", "addressLine3"],
                                    disabled: (!editMode),
                                    form: formik
                                })}
                            </Grid>

                            <Grid item xs={12} sm={12} md={12} lg={12}>
                                {FieldUtils.getProfileComboField({
                                    label: "",
                                    valueName: "district",
                                    dataList: ComboData.district,
                                    getOptionLabel: (option) => option.type? intl.formatMessage({ id: option.type }) : "",
                                    disabled: (!editMode),
                                    form: formik
                                })}
                            </Grid>

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

                        </Grid>
                    </Grid>
                </form>
            }
        </MainCard>
    );
};

export default UserInformationCard_Individual_Pub;
