// material-ui
import {
    Grid, Button, Typography,
    Dialog, DialogTitle, DialogContent, DialogActions,
    FormHelperText, 
    // TextField
} from '@mui/material';
import MainCard from "components/MainCard";
import * as React from "react";
import * as yup from 'yup';
import { useEffect, useState } from "react";
import * as DateUtils from 'utils/DateUtils';
import * as HttpUtils from 'utils/HttpUtils';
import * as UrlUtils from "utils/ApiPathConst";
import * as FieldUtils from "utils/FieldUtils";
import * as ComboData from "utils/ComboData";
import { useNavigate } from "react-router-dom";
import { useFormik } from 'formik';
const LoadingComponent = Loadable(lazy(() => import('../../extra-pages/LoadingComponent')));
import Loadable from 'components/Loadable';
import { lazy } from 'react';
import { notifyCreateSuccess } from 'utils/CommonFunction';
import { useIntl } from "react-intl";

import {DatePicker} from "@mui/x-date-pickers/DatePicker";
import dayjs from "dayjs";
import {DemoItem} from "@mui/x-date-pickers/internals/demo";
import {LocalizationProvider} from "@mui/x-date-pickers/LocalizationProvider";
import {AdapterDayjs} from "@mui/x-date-pickers/AdapterDayjs";
// ==============================|| DASHBOARD - DEFAULT ||============================== //


const OrganizationCard_loadFromUser = ({ userData, userId }) => {
    const intl = useIntl();
    const [currentUserData, setCurrentUserData] = useState(userData);
    const navigate = useNavigate();
    const [onReady, setOnReady] = useState(false);
    const [isFailPopUp, setIsFailPopUp] = useState(false);
    const [failText, setFailText] = useState("");
    const [errorMsg, setErrorMsg] = useState("");
    const [minDate] = React.useState(new Date().setDate(new Date().getDate() + 1));
    const [fromDate, setFromDate] = React.useState(null);
    const [fromDateValue, setFromDateValue] = React.useState(null);

    useEffect(() => {
        //if state data are ready and assign to different field
        // console.log(currentApplicationDetailData)
        if (Object.keys(currentUserData).length > 0) {
            if(DateUtils.dateValue(currentUserData.brExpiryDate)>DateUtils.dateValue(minDate)){
                setFromDate(currentUserData.brExpiryDate);
            }else{
                setErrorMsg("Please select a date after today.")
            }
            // setFromDate(currentUserData.brExpiryDate)
            setOnReady(true);
        }
    }, [currentUserData]);

    React.useEffect(() => {
        setFromDateValue(fromDate);
    }, [fromDate]);

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

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: currentUserData,
        validationSchema: yup.object().shape({
            enCompanyName: yup.string().max(255, displayErrorMsg(intl.formatMessage({ id: 'userRequireEnglishName' }))).required(displayErrorMsg(intl.formatMessage({ id: 'userRequireEnglishName' }))),
            chCompanyName: yup.string().max(255, displayErrorMsg(intl.formatMessage({ id: 'userRequireChineseName' }))).nullable(),
            addressLine1: yup.string().max(40).required(displayErrorMsg(intl.formatMessage({ id: 'validateAddressLine1' }))),
            addressLine2: yup.string().max(40).nullable(),
            addressLine3: yup.string().max(40).nullable(),
            fax_countryCode: yup.string().min(3, displayErrorMsg(intl.formatMessage({ id: 'requireDialingCode' }))).nullable(),
            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).nullable(),
            brExpiryDate: yup.string().min(8).required(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 => {
            if (values.country == null) {
                setErrorMsg(intl.formatMessage({ id: 'pleaseFillInCountry' }))
            } else {
                if (values.country.type == "hongKong" && values.district == null) {
                    setErrorMsg(intl.formatMessage({ id: 'pleaseFillInDistrict' }))
                } else {
                    let sentDateFrom = "";
                    if (fromDateValue == null) {
                        setErrorMsg(intl.formatMessage({ id: 'pleaseFillInBusinessRegCertValidityDate' }))
                    }else{
                        sentDateFrom = DateUtils.dateValue(fromDateValue)
                        HttpUtils.post({
                            url: UrlUtils.POST_ORG_SAVE_PATH,
                            params: {
                                id: null,
                                primaryUserId: userId,
                                enCompanyName: values.enCompanyName,
                                chCompanyName: values.chCompanyName,
                                brNo: values.brNo,
                                brExpiryDate: sentDateFrom,
                                enCompanyNameTemp: values.enCompanyNameTemp,
                                chCompanyNameTemp: values.chCompanyNameTemp,
                                brExpiryDateTemp: values.brExpiryDateTemp,
                                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 (responseData) {
                                if (responseData.msg) {
                                    setFailText(responseData.msg);
                                    setIsFailPopUp(true);
                                    return;
                                }
                                navigate('/org/' + responseData.id);
                                notifyCreateSuccess()
                            }
                        });
                    }

                }
            }
        }
    });

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

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

            {/* <div style={{ border: "solid 1px;", color: "red" }}>
                    TODO: Error Summary
                    {Object.values(formik.errors).map(error => (
                        <div>{error}</div>
                    ))}
                </div> */}



            <div style={{ padding: 24 }}>
                <form onSubmit={formik.handleSubmit}>
                    {!onReady ?
                        <LoadingComponent />
                        :
                        <Grid container spacing={1}>
                            {/*top*/}
                            <Grid item s={12} md={12} lg={12} sx={{ mb: 3 }} alignItems={"start"} justifyContent="center">
                                <Grid item sx={{ mr: 3 }}>
                                    <Button
                                        size="large"
                                        variant="contained"
                                        type="submit"
                                        sx={{
                                            textTransform: 'capitalize',
                                            alignItems: 'end'
                                        }}
                                    >
                                        Create
                                    </Button>
                                </Grid>
                            </Grid>
                            {/*top*/}

                            <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: "BR No.:",
                                    valueName: "brNo",
                                    form: formik
                                })}
                            </Grid>

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

                            <Grid item xs={12} lg={4}>
                                {FieldUtils.getTextField({
                                    label: FieldUtils.notNullFieldLabel("Name (Eng):"),
                                    valueName: "enCompanyName",
                                    form: formik
                                })}
                            </Grid>

                            <Grid item xs={12} lg={4}>
                                {FieldUtils.getTextField({
                                    label: "Name (Ch):",
                                    valueName: "chCompanyName",
                                    form: formik
                                })}
                            </Grid>

                            <Grid item xs={12} lg={4} >
                                <Grid container alignItems={"center"}>
                                    <Grid item xs={12} md={3} lg={3} sx={{ display: 'flex', alignItems: 'center' }}>
                                        <Typography variant="pnspsFormParagraphBold">{FieldUtils.notNullFieldLabel("Expiry Date:")}</Typography>
                                    </Grid>
                                    <Grid item xs={12} md={6} lg={6}>
                                        <LocalizationProvider dateAdapter={AdapterDayjs} localeText={DateUtils.getPickerLocaleText(intl.locale)}>
                                            <DemoItem  components={['DatePicker']}>
                                                <DatePicker
                                                    id="brExpiryDate"
                                                    name="brExpiryDate"
                                                    // onError={Boolean(formik.errors["brExpiryDate"])}
                                                    slotProps={{
                                                        field: { readOnly: true, },
                                                        // textField: {
                                                        //     helperText:formik.errors["brExpiryDate"] ? formik.errors["brExpiryDate"] : ''
                                                        // },
                                                    }}
                                                    format="DD/MM/YYYY"
                                                    // label={"Submit Date (From)"}
                                                    value={fromDate == null ? null : dayjs(fromDate)}
                                                    minDate={minDate == null ? null : dayjs(minDate)}
                                                    // disabled={(!editMode && !createMode)}
                                                    onChange={(newValue) => {
                                                        setErrorMsg("")
                                                        if(DateUtils.dateValue(newValue)>DateUtils.dateValue(new Date())){
                                                            setFromDate(newValue);
                                                        }else{
                                                            setErrorMsg("Please select a date after today.")
                                                        }
                                                    }}
                                                />
                                            </DemoItem >
                                        </LocalizationProvider>
                                        {/* <TextField
                                            fullWidth
                                            id="brExpiryDate"
                                            name="brExpiryDate"
                                            type="date"
                                            inputProps={{ min: DateUtils.dateValue(new Date()) }}
                                            error={Boolean(formik.errors["brExpiryDate"])}
                                            helperText={formik.errors["brExpiryDate"] ? formik.errors["brExpiryDate"] : ''}
                                            onChange={formik.handleChange}
                                            value={formik.values["brExpiryDate"]}
                                            sx={{
                                                width: '100%'
                                            }}
                                        /> */}
                                    </Grid>
                                </Grid>

                            </Grid>

                            <Grid item xs={12} lg={4}>
                                {FieldUtils.getTextField({
                                    label: FieldUtils.notNullFieldLabel("Contact Person:"),
                                    valueName: "contactPerson",
                                    form: formik
                                })}
                            </Grid>

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

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

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

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

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

                        </Grid>
                    }
                </form>
            </div>

            <div>
                <Dialog
                    open={isFailPopUp}
                    onClose={() => setIsFailPopUp(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">Action Fail</Typography></DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h4" style={{ padding: '16px' }}>{failText}</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setIsFailPopUp(false)}><Typography variant="h5">OK</Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
        </MainCard>
    );
};

export default OrganizationCard_loadFromUser;
