// material-ui
import {
    Grid,
    Typography,
    Button,
    RadioGroup,
    Dialog, DialogTitle, DialogContent, DialogActions,
    Stack, Box
} from '@mui/material';
import { useFormik } from 'formik';
import * as yup from 'yup';
import * as React from "react";
import * as HttpUtils from "utils/HttpUtils";
import * as UrlUtils from "utils/ApiPathConst";
import * as FieldUtils from "utils/FieldUtils";
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
import ForwardIcon from '@mui/icons-material/Forward';
import {
    isORGLoggedIn,
  } from "utils/Utils";

import { useNavigate } from "react-router-dom";
import { notifyActionSuccess } from 'utils/CommonFunction';
import {PNSPS_LONG_BUTTON_THEME} from "../../../themes/buttonConst";
import {ThemeProvider} from "@emotion/react";
import {FormattedMessage, useIntl} from "react-intl";

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

const PublicNoticeApplyForm = ({ loadedData, selections }) => {
    const [isWarningPopUp, setIsWarningPopUp] = React.useState(false);
    const [warningText, setWarningText] = React.useState("");
    const [attachment, setAttachment] = React.useState({});
    const intl = useIntl();

    const [val, setVal] = React.useState({});
    const [reloadPage, setReloadPage] = React.useState(false);

    const [issueId, setIssueId] = React.useState(loadedData.issueId);
    const navigate = useNavigate();

    const BackgroundHead = {
        backgroundImage: `url(${titleBackgroundImg})`,
        width: 'auto',
        height: 'auto',
        backgroundSize: 'contain',
        backgroundRepeat: 'no-repeat',
        backgroundColor: '#0C489E',
        backgroundPosition: 'right'
    }

    // React.useEffect(()=>{
    //     loadedData.careOf = loadedData.contactPerson
    // },[]);

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: loadedData,
        validationSchema: yup.object().shape({
            contactPerson: yup.string().max(40, intl.formatMessage({id: 'noMoreThen40Words'})).required(intl.formatMessage({id: 'requireContactPerson'})),
            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'})),
            remarks: yup.string().max(255,intl.formatMessage({id: 'noMoreThen255Words'})).nullable(),
        }),
        onSubmit: values => {
            if (!values.issueId) {
                setWarningText(intl.formatMessage({id: 'requireTargetVol'}));
                setIsWarningPopUp(true);
                return;
            }
            if (!attachment) {
                setWarningText(intl.formatMessage({id: 'requireFile'}));
                setIsWarningPopUp(true);
                return;
            } else if (!attachment.size || attachment.size <= 0) {
                setWarningText(intl.formatMessage({id: 'requireValidFile'}));
                setIsWarningPopUp(true);
                return;
            } else if (attachment.size >= (10 * 1024 * 1034)) {
                setWarningText(intl.formatMessage({id: 'fileSizeWarning'}));
                setIsWarningPopUp(true);
                return;
            }
            if(isORGLoggedIn()){
                HttpUtils.get({
                    url: UrlUtils.CHECK_OVERDUE,
                    onSuccess: (responData)=>{
                        if(responData.haveOverdue){
                            setVal(values);
                            setWarningText(intl.formatMessage({id: 'dnOverdueWarning'}));
                            setIsWarningPopUp(true);
                        }else{
                            apply(values);
                        }
                    }
                });
            }else{
                apply(values);
            }
           
        }
    });

    const apply = (values)=>{
        HttpUtils.postWithFiles({
            url: UrlUtils.POST_PUBLIC_NOTICE_APPLY,
            params: {
                id: 0,
                contactPerson: values.contactPerson,
                contactTelNo: {
                    countryCode: values.tel_countryCode,
                    phoneNumber: values.phoneNumber
                },
                contactFaxNo: {
                    countryCode: values.fax_countryCode,
                    faxNumber: values.faxNumber
                },
                issueId: issueId,
                careOf: values.careOf ? values.careOf: "",
                remarks: values.remarks ? values.remarks : "",
            },
            files: [attachment],
            onSuccess: function (responData) {
                if(responData.msg){
                    setVal({});
                    setReloadPage(true);
                    setWarningText(intl.formatMessage({id: responData.msg}));
                    setIsWarningPopUp(true);
                    return;
                }
                notifyActionSuccess(intl.formatMessage({id: 'submissionSuccess'}) + '!')
                navigate("/publicNotice");
                // location.reload(); 
            }
        });
    }

    const readFile = (event) => {
        let file = event.target.files[0];
        if (file) {
            if (file.name.toLowerCase().substr(file.name.length - 4).includes(".doc")
                || file.name.toLowerCase().substr(file.name.length - 5).includes(".docx")
                || file.name.toLowerCase().substr(file.name.length - 4).includes(".xls")
                || file.name.toLowerCase().substr(file.name.length - 5).includes(".xlsx")
            ) {
                setAttachment(event.target.files[0]);
            } else {
                setWarningText(intl.formatMessage({id: 'requireValidFileWithFormat'}));
                setIsWarningPopUp(true);
                setAttachment({});
                document.getElementById("uploadFileBtn").value = "";
                return;
            }
        }
    }


    return (
        <Grid container sx={{ minHeight: '95vh', backgroundColor: '#ffffff', mb: 3 }} direction="column" alignItems="center">
            <Grid item xs={12} md={12} width="100%" >
                <div style={BackgroundHead}>
                    <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
                        <Typography ml={15} color='#FFF' variant="h4" sx={{display: { xs: 'none', sm: 'none', md: 'block' }}}>
                            <FormattedMessage id="applyPublicNotice"/>
                        </Typography>
                    </Stack>
                </div>
            </Grid>
            <Grid item xs={12} width={{xs:"90%", sm:"90%", md:"60%", lg:"60%"}}>
                <Button
                    aria-label={intl.formatMessage({id: 'back'})}
                    title={intl.formatMessage({id: 'back'})}
                    sx={{ ml: 0, mt: 2.5 }} style={{ border: '2px solid' }} variant="outlined" onClick={() => { navigate(-1) }}
                >
                    <ForwardIcon style={{ height: 30, width: 50, transform: "rotate(180deg)" }} />
                </Button>
            </Grid>
            {/* <Grid item xs={12}>
                    <Typography variant="pnspsFormParagraphBold">申請公共啟事</Typography>
                </Grid> */}
            <Grid item xs={12} md={12} width={{ md: "60%", xs: "90%" }}>
                <Box xs={12} mt={1} sx={{ p: 2, border: '3px groove grey', borderRadius: '10px' }}>
                    <form onSubmit={formik.handleSubmit}>
                        <Grid container spacing={1} sx={{ minHeight: '80vh' }} direction="row" justifyContent="flex-start" alignItems="center">
                            <Grid item xs={12} md={12} lg={12} sx={{ mb: 1 }}>
                                {FieldUtils.getTextField({
                                    label: intl.formatMessage({id: 'contactPerson'}) + ":",
                                    valueName: "contactPerson",
                                    form: formik,
                                    disabled: true
                                })}
                            </Grid>
                            <Grid item xs={12} md={12}>
                                {FieldUtils.getPhoneField({
                                    label: intl.formatMessage({id: 'userContactNumber'}) + ":",
                                    disabled: true,
                                    valueName: {
                                        code: "tel_countryCode",
                                        num: "phoneNumber",
                                    },
                                    form: formik
                                })}
                            </Grid>
                            <Grid item xs={12} md={12}>
                                {FieldUtils.getPhoneField({
                                    label: intl.formatMessage({id: 'contactFaxNumber'}) + ":",
                                    disabled: true,
                                    valueName: {
                                        code: "fax_countryCode",
                                        num: "faxNumber",
                                    },
                                    form: formik
                                })}
                            </Grid>
                            <Grid item xs={12} lg={12}>
                                <Grid container alignItems={"center"}>
                                    <Grid item xs={12} md={3} lg={3}
                                        sx={{ display: 'flex', alignItems: 'center' }}>
                                        <Typography variant="pnspsFormParagraphBold">
                                            <FormattedMessage id="targetVol" />:
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12} md={9} lg={6}>
                                        <RadioGroup
                                            aria-labelledby="radio-buttons-group-label"
                                            id="issueId"
                                            name="issueId"
                                            defaultValue={issueId}
                                            onChange={(event) => {
                                                setIssueId(event.target.value);
                                            }}
                                        >
                                            {
                                                selections
                                            }
                                        </RadioGroup>
                                    </Grid>
                                </Grid>
                            </Grid>
                            <Grid item xs={12} md={12} lg={12}>
                                <Grid container direction="row" justifyContent="flex-start" alignItems="center">
                                    <Grid item xs={12} md={3} lg={3}
                                        sx={{ display: 'flex', alignItems: 'center' }}>
                                        <Typography variant="pnspsFormParagraphBold">
                                            <FormattedMessage id="draftFile"/> ({intl.formatMessage({id: 'fileSizeWarning'})}):
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12} md={6} lg={6} sx={{ wordBreak: 'break-word' }}>
                                        <input
                                            id="uploadFileBtn"
                                            name="file"
                                            type="file"
                                            accept=".doc,.docx,.xls,.xlsx"
                                            style={{ display: 'none' }}
                                            onChange={(event) => {
                                                readFile(event)
                                            }}
                                        />
                                        {attachment.name}
                                    </Grid>
                                    {/* <Grid item xs={12} md={3} lg={3}>
                                        <label htmlFor="uploadFileBtn">
                                            <Button
                                                aria-label={intl.formatMessage({id: 'uploadFileBtn'})}
                                                component="span"
                                                variant="outlined"
                                                size="large"
                                            >{attachment ? intl.formatMessage({id: 'uploadFileBtn'}) : intl.formatMessage({id: 'reUpload'})}</Button>
                                        </label>
                                    </Grid> */}
                                </Grid>
                            </Grid>
                            <Grid item xs={12} md={12} lg={12}>
                                <Grid container direction="row" justifyContent="flex-start" alignItems="center">
                                    <Grid item xs={12} md={3} lg={3}
                                        sx={{ display: 'flex', alignItems: 'center' }}>
                                    </Grid>
                                    <Grid item xs={12} md={6} lg={6} >
                                        <label htmlFor="uploadFileBtn">
                                            <Button
                                                aria-label={intl.formatMessage({id: 'uploadFileBtn'})}
                                                component="span"
                                                variant="outlined"
                                                size="large"
                                            >{attachment ? intl.formatMessage({id: 'uploadFileBtn'}) : intl.formatMessage({id: 'reUpload'})}</Button>
                                        </label>
                                    </Grid>
                                    <Grid item xs={12} md={3} lg={3}>
                                    </Grid>
                                </Grid>
                            </Grid>
                            {isORGLoggedIn()?
                                <Grid item xs={12} md={12} lg={12} sx={{ mb: 1 }}>
                                    {FieldUtils.getTextField({
                                        label: "Care Of:",
                                        valueName: "careOf",
                                        form: formik,
                                        // disabled: true
                                    })}
                                </Grid>:null
                            }
                            <Grid item xs={12} md={12} lg={12}>
                                {FieldUtils.getTextArea({
                                    label: intl.formatMessage({id: 'extraMark'}) + ":",
                                    valueName: "remarks",
                                    form: formik,
                                    inputProps: { maxLength: 255 }
                                })}
                            </Grid>
                            <Grid item xs={12}>
                                <center>
                                    <ThemeProvider theme={PNSPS_LONG_BUTTON_THEME}>
                                    <Button
                                        aria-label={intl.formatMessage({id: 'applyPublicNotice'})}
                                        variant="contained"
                                        type="submit"
                                    >
                                        <FormattedMessage id="applyPublicNotice"/>
                                    </Button>
                                    </ThemeProvider>
                                </center>
                            </Grid>
                        </Grid>
                    </form>
                </Box>
            </Grid>
            <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>
                        <FormattedMessage id="attention"/>
                    </DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h3" style={{ padding: '16px' }}>{warningText}</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button
                            aria-label={intl.formatMessage({id: 'ok'})}
                            onClick={() => {
                                if(val.contactPerson){
                                    apply(val);
                                    setIsWarningPopUp(false);
                                }else{
                                    setIsWarningPopUp(false);
                                    if(reloadPage){
                                        location.reload();
                                    }
                                }
                            }}
                        >
                            <FormattedMessage id="ok" />
                        </Button>
                    </DialogActions>
                </Dialog>
            </div>
        </Grid>
    );
};


export default PublicNoticeApplyForm;
