// material-ui
import {
    Grid, Button,
    // Checkbox, FormControlLabel,
    Typography,
    Dialog, DialogTitle, DialogContent, DialogActions,
    FormHelperText, CircularProgress,
} from '@mui/material';
// import { FormControlLabel } from '@material-ui/core';
import MainCard from "components/MainCard";
import * as React from "react";
import { useFormik } from 'formik';
import * as yup from 'yup';
import { useEffect, useState } from "react";
import * as HttpUtils from 'utils/HttpUtils';
import * as UrlUtils from "utils/ApiPathConst";
import * as FieldUtils from "utils/FieldUtils";
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 { FormattedMessage, useIntl } from "react-intl";
import { PNSPS_BUTTON_THEME } from "themes/buttonConst";
import { ThemeProvider } from "@emotion/react";

// ==============================|| DASHBOARD - DEFAULT ||============================== //


const OrganizationPubCard = ({ userData, loadDataFun, id, setEditModeFun }) => {
    const intl = useIntl();
    const [creditorConfirmPopUp, setCreditorConfirmPopUp] = React.useState(false);
    const [nonCreditorConfirmPopUp, setNonCreditorConfirmPopUp] = React.useState(false);

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

    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({
            addressLine1: yup.string().max(40).required(displayErrorMsg(intl.formatMessage({ id: 'validateAddressLine1' }))),
            addressLine2: yup.string().max(40, displayErrorMsg(intl.formatMessage({ id: 'noMoreThen40Words' }))),
            addressLine3: yup.string().max(40, displayErrorMsg(intl.formatMessage({ id: 'noMoreThen40Words' }))),
            tel_countryCode: yup.string().min(3, displayErrorMsg(intl.formatMessage({ id: 'requireDialingCode' }))),
            phoneNumber: yup.string().min(8, displayErrorMsg(intl.formatMessage({ id: 'requiredValidNumber' }))).required(displayErrorMsg(intl.formatMessage({ id: 'requireContactNumber' }))),
            faxNumber: yup.string().min(8, displayErrorMsg(intl.formatMessage({ id: 'require8Number' }))).nullable(),
        }),
        onSubmit: (values) => {
            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, reject) => {
                HttpUtils.post({
                    url: UrlUtils.POST_PUB_ORG_SAVE_PATH,
                    params: {
                        contactPerson: values.contactPerson,
                        contactTel: {
                            countryCode: values.tel_countryCode,
                            phoneNumber: values.phoneNumber
                        },
                        faxNo: {
                            countryCode: values.fax_countryCode,
                            faxNumber: values.faxNumber
                        },
                        addressTemp: {
                            country: values.country.type,
                            district: values.district?.type,
                            addressLine1: values.addressLine1,
                            addressLine2: values.addressLine2,
                            addressLine3: values.addressLine3,
                        },
                    },
                    onSuccess: function () {
                        notifySaveSuccess()
                        loadDataFun();
                        setEditMode(false);
                        resolve();
                    },
                    onFail: () => reject(),
                    onError: () => reject(),
                });
            });
        }
    });

    useEffect(() => {
        setEditModeFun(editMode);
    }, [editMode]);

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

    // useEffect(() => {
    //     if (Object.keys(userData).length > 0) {
    //         if(userData.creditor === undefined||userData.creditor === null){
    //             userData.creditor = false
    //         }
    //         setCurrentUserData(userData);
    //     }
    // }, []);

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

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

            <form onSubmit={formik.handleSubmit} style={{ padding: 24 }}>

                {/*top*/}
                <Grid item s={12} md={12} lg={12} sx={{ mb: 3 }} alignItems={"start"} justifyContent="center">
                    <Grid container maxWidth justifyContent="flex-start">

                        {editMode ?
                            <>
                                {createMode ?
                                    <>
                                        <Grid item sx={{ ml: 0, mr: 3 }}>
                                            <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                                <Button
                                                    variant="contained"
                                                    type="submit"
                                                    color="success"
                                                    disabled={formik.isSubmitting}
                                                    startIcon={formik.isSubmitting ? <CircularProgress color="inherit" size={18} /> : null}
                                                >
                                                    <FormattedMessage id="create" />
                                                </Button>
                                            </ThemeProvider>
                                        </Grid>
                                    </> :
                                    <>
                                        <Grid item sx={{ ml: 0, mr: 3 }}>
                                            <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                                <Button
                                                    variant="contained"
                                                    color="cancel"
                                                    onClick={loadDataFun}
                                                >
                                                    <FormattedMessage id="resetAndBack" />
                                                </Button>
                                            </ThemeProvider>
                                        </Grid>
                                        <Grid item sx={{ ml: 3, mr: 3 }}>
                                            <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                                <Button
                                                    variant="contained"
                                                    type="submit"
                                                    color="success"
                                                    disabled={formik.isSubmitting}
                                                    startIcon={formik.isSubmitting ? <CircularProgress color="inherit" size={18} /> : null}
                                                >
                                                    <FormattedMessage id="save" />
                                                </Button>
                                            </ThemeProvider>
                                        </Grid>
                                    </>
                                }
                            </>
                            :
                            <>
                                <Grid item sx={{ ml: 0, mr: 3 }}>
                                    <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                        <Button
                                            variant="contained"
                                            onClick={onEditClick}
                                            color="success"
                                        >
                                            <   FormattedMessage id="edit" />
                                        </Button>
                                    </ThemeProvider>
                                </Grid>
                            </>
                        }
                    </Grid>
                </Grid>
                {/*top*/}

                {!onReady ?
                    <LoadingComponent />
                    :
                    <Grid container spacing={1}>
                        {/* <Grid item xs={12}>
                            <Typography variant="h4" sx={{ mb: 2, mr: 3, borderBottom: "1px solid black" }}>
                                <FormattedMessage id="organizationDetails" />
                            </Typography>
                        </Grid> */}
                        <Grid item xs={12}>
                            <FormHelperText error id="helper-text-address1-signup">
                                <Typography variant="errorMessage1">
                                    {errorMsg}
                                </Typography>
                            </FormHelperText>
                        </Grid>
                        <Grid item xs={12} lg={4} >
                            {FieldUtils.getTextField({
                                label: intl.formatMessage({ id: 'brNo' }) + ":",
                                valueName: "brNo",
                                disabled: true,
                                form: formik
                            })}
                        </Grid>
                        <Grid item xs={12} lg={4} >
                            {FieldUtils.getTextField({
                                label: FieldUtils.notNullFieldLabel(intl.formatMessage({ id: 'expiryDate' }) + ":"),
                                valueName: "brExpiryDate",
                                disabled: true,
                                form: formik
                            })}

                        </Grid>

                        <Grid item xs={12} lg={4} ></Grid>

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

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

                        <Grid item xs={12} lg={4} >

                        </Grid>

                        <Grid item xs={12} lg={4} >
                            {FieldUtils.getTextField({
                                label: FieldUtils.notNullFieldLabel(intl.formatMessage({ id: 'contactPerson' }) + ":"),
                                valueName: "contactPerson",
                                disabled: (!editMode && !createMode),
                                form: formik
                            })}
                        </Grid>

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

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

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

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

                        <Grid item lg={12} ></Grid>

                    </Grid>
                }
            </form>
            <div>
                <Dialog
                    open={creditorConfirmPopUp}
                    onClose={() => setCreditorConfirmPopUp(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' }}>Are you sure mark as Credit Client?</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setCreditorConfirmPopUp(false)}><Typography variant="h5">Cancel</Typography></Button>
                        <Button onClick={() => markAsCreditor()}><Typography variant="h5">Confirm</Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
            <div>
                <Dialog
                    open={nonCreditorConfirmPopUp}
                    onClose={() => setNonCreditorConfirmPopUp(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' }}>Are you sure mark as Non-Credit Client?</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setNonCreditorConfirmPopUp(false)}><Typography variant="h5">Cancel</Typography></Button>
                        <Button onClick={() => markAsNonCreditor()}><Typography variant="h5">Confirm</Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
        </MainCard>
    );
};

export default OrganizationPubCard;
