// material-ui
import {
    Dialog, DialogTitle, DialogContent, DialogActions,
    Typography,
    Grid,
    Stack,
    TextField,
    FormLabel,
    Button,
    RadioGroup, Radio,
    FormControlLabel
} from '@mui/material';
import * as UrlUtils from "utils/ApiPathConst";
import * as HttpUtils from "utils/HttpUtils";
import FileList from "components/FileList"
import MainCard from "components/MainCard";
import * as React from "react";
import * as yup from 'yup';
import { useParams } from "react-router-dom";
import { useFormik } from 'formik';
import { useNavigate } from "react-router-dom";
import * as DateUtils from "utils/DateUtils"
import Loadable from 'components/Loadable';
import { notifyActionSuccess } from 'utils/CommonFunction';
import {PNSPS_BUTTON_THEME} from "themes/buttonConst";
import {ThemeProvider} from "@emotion/react";
import {FormattedMessage, useIntl} from "react-intl";
const UploadFileTable = Loadable(React.lazy(() => import('./UploadFileTable')));
import * as ProofStatus from "utils/statusUtils/ProofStatus";

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


const FormPanel = ({ formData }) => {
    const intl = useIntl();
    const { locale } = intl;
    const [data, setData] = React.useState({});
    const [attachments, setAttachments] = React.useState([]);

    const [actionValue, setActionValue] = React.useState(true);

    const [isWarningPopUp, setIsWarningPopUp] = React.useState(false);
    const [warningText, setWarningText] = React.useState("");

    const navigate = useNavigate()
    const params = useParams();

    React.useEffect(() => {
        if (formData) {
            setData(formData);
        }
    }, [formData]);

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: data,
        validationSchema: yup.object().shape({
            vaild: yup.string().max(255, intl.formatMessage({id: 'requireLoginPassword'})).required(intl.formatMessage({id: 'requireLoginPassword'})),
        }),
        onSubmit: values => {
            if (!actionValue) {
                if (!attachments || attachments.length <= 0) {
                    setWarningText(intl.formatMessage({id: 'requireFile'}));
                    setIsWarningPopUp(true);
                    return;
                }
            }

            if (isOverTime()) {
                setWarningText("回覆逾時，請重新申請。");
                setIsWarningPopUp(true);
                return;
            }
            // console.log(values);
            HttpUtils.postWithFiles({
                url: UrlUtils.REPLY_PROOF,
                params: {
                    id: data.id,
                    action: actionValue,
                    vaild: values.vaild,
                },
                files: attachments ? attachments : [],
                onSuccess: function () {
                    notifyActionSuccess("提交成功!")
                    if (actionValue) {
                        if(data.creditor){
                            navigate("/proof/search");
                        }else{
                            navigate("/proof/pay/" + params.id);
                        }
                    } else {
                        navigate("/proof/search");
                    }
                },
                onFail: function (response) {
                    setWarningText(intl.formatMessage({id: 'actionFail'}));
                    setIsWarningPopUp(true);
                    console.log(response);
                },
                onError: function (error) {
                    setWarningText(intl.formatMessage({id: 'actionFail'}));
                    setIsWarningPopUp(true);
                    console.log(error);
                }
            });
        }
    });

    const readFile = (event) => {
        let file = event.target.files[0];
        if (file) {
            if (!file.name.toLowerCase().substr(file.name.length - 4).includes(".pdf")) {
                setWarningText(intl.formatMessage({id: 'requireValidFileWithPdfFormat'}));
                setIsWarningPopUp(true);
                document.getElementById("uploadFileBtn").value = "";
                return;
            }
            if (file.size >= (10 * 1024 * 1034)) {
                setWarningText(intl.formatMessage({id: 'fileSizeWarning'}));
                setIsWarningPopUp(true);
                return;
            }

            file['id'] = attachments.length;
            setAttachments([
                ...attachments,
                file
            ]);
            document.getElementById("uploadFileBtn").value = "";
        }
    }

    const isOverTime = () => {
        let proofPaymentDeadline = DateUtils.convertToDate(formik.values?.proofPaymentDeadline);
        if (!proofPaymentDeadline) return true;
        let current = new Date();
        return current.getTime() > proofPaymentDeadline;
    }



    return (
        <MainCard xs={12} sm={12} md={12} lg={12}
            border={false}
            content={false}>

            <Typography variant="h4" sx={{ textAlign: "left", mb: 2, borderBottom: "1px solid black" }}>
                <FormattedMessage id="publicNoticePaymentProofComment"/>
            </Typography>

            <form onSubmit={formik.handleSubmit}>

                {
                    formik.values.replyDate ?
                        <Grid container direction="column" sx={{ paddingLeft: 0, paddingRight: 0 }}>
                            <Grid item xs={12} sm={12} md={12} lg={8} textAlign="left">
                                <Typography variant="h5">
                                    <FormattedMessage id="proofReplyDate" /> :&nbsp;
                                    {
                                        locale === 'en' ?
                                            DateUtils.dateStr(formik.values.replyDate)
                                            :
                                            DateUtils.datetimeStr_Cht(formik.values.replyDate)
                                    }
                                </Typography>
                            </Grid>
                            <Grid item xs={12} md={12} textAlign="left">
                                <Typography variant="h5">
                                    <FormattedMessage id="proofReply" /> : {formik.values.action ?
                                    (<span style={{ color: 'green' }}>
                                        <FormattedMessage id="proofErrorFree" />
                                    </span>)
                                    :
                                    (<span style={{ color: 'red' }}>
                                        <FormattedMessage id="proofWithError" />
                                    </span>)}
                                </Typography>
                            </Grid>
                            <Grid item xs={12} md={12} textAlign="left">
                                <Typography variant="h5">
                                    <FormattedMessage id="proofReply" /> :&nbsp;
                                    <span style={{ color: 'green' }}>
                                        {
                                        locale === 'en' ? 
                                            ProofStatus.getStatusText_Eng(formik.values).text
                                            : 
                                            ProofStatus.getStatusText_Cht(formik.values).text
                                        }
                                    </span>
                                </Typography>
                            </Grid>
                            {
                                formik.values.action ?
                                    null
                                    :
                                    <Grid item xs={12} md={12} textAlign="left" sx={{ width:'95%', maxWidth: {xs:'70vw', sm:'72vw', md:'75vw',lg:'80vw'}}}>
                                        <FileList
                                            lang="ch"
                                            refId={params.id}
                                            refType={"proofReply"}
                                            dateHideable={true}
                                            disablePagination
                                            disableSelectionOnClick
                                            disableColumnMenu
                                            disableColumnSelector
                                            hideFooter
                                        />
                                    </Grid>
                            }

                        </Grid>
                        :
                        (
                            isOverTime() ?
                                <Grid container direction="column" sx={{ paddingLeft: 0, paddingRight: 0 }} spacing={1}>
                                    <Grid item xs={12} md={12} textAlign="left">
                                        <Typography variant="h5">回覆逾時，請重新申請。</Typography>
                                    </Grid>
                                </Grid>
                                :
                                <Grid container direction="column" sx={{ paddingLeft: 0, paddingRight: 0 }} spacing={1}>

                                    <Grid item xs={12} md={12}>
                                        <RadioGroup
                                            aria-labelledby="demo-radio-buttons-group-label"
                                            id="action"
                                            name="action"
                                            defaultValue={true}
                                            onChange={(event) => {
                                                setActionValue(event.target.value === "true" ? true : false);
                                            }}
                                        >
                                            <FormControlLabel value={true} control={<Radio />} label={intl.formatMessage({id: 'proofErrorFree'})} />
                                            <FormControlLabel value={false} control={<Radio />} label={intl.formatMessage({id: 'proofWithError'})} />
                                        </RadioGroup>
                                    </Grid>


                                    {
                                        actionValue ?
                                            null
                                            :
                                            <>
                                                <Grid item xs={12} md={12} textAlign="left">
                                                    <Typography variant="h5">
                                                        <FormattedMessage id="requiredUploadFix" />：
                                                    </Typography>
                                                </Grid>

                                                <Grid item xs={12} md={12} textAlign="left">
                                                    <input
                                                        id="uploadFileBtn"
                                                        name="file"
                                                        type="file"
                                                        accept=".pdf"
                                                        style={{ display: 'none' }}
                                                        disabled={attachments.length >= (formik.values.groupType === "Private Bill" ? 2 : 1)}
                                                        onChange={(event) => {
                                                            readFile(event)
                                                        }}
                                                    />
                                                    <label htmlFor="uploadFileBtn">
                                                        <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                                        <Button
                                                            color="save"
                                                            component="span"
                                                            variant="contained"
                                                            aria-label={intl.formatMessage({id: 'upload'})}
                                                            disabled={attachments.length >= (formik.values.groupType === "Private Bill" ? 2 : 1)}
                                                        >
                                                            <FormattedMessage id="upload" />
                                                        </Button>
                                                        </ThemeProvider>
                                                    </label>
                                                </Grid>


                                                <Grid item xs={12} sm={12} md={12} lg={12} textAlign="left" sx={{ width:'95%', maxWidth: {xs:'70vw', sm:'72vw', md:'75vw',lg:'80vw'}}} >
                                                    <UploadFileTable key="uploadTable" recordList={attachments} setRecordList={setAttachments} />
                                                </Grid>
                                            </>
                                    }

                                    <Grid item xs={12} sm={12} md={12} lg={12}>
                                        <Stack direction="row" alignItems="center">
                                            <FormLabel sx={{ paddingRight: 2, paddingBottom: 3, textAlign: "center" }}>
                                                <Typography variant="h5">
                                                    <FormattedMessage id="sign" />：
                                                </Typography>
                                            </FormLabel>
                                            <TextField
                                                fullWidth
                                                type="password"
                                                onChange={formik.handleChange}
                                                name="vaild"
                                                variant="outlined"
                                                error={Boolean(formik.errors["vaild"])}
                                                helperText={formik.errors["vaild"] ? formik.errors["vaild"] : ' '}
                                                placeholder={intl.formatMessage({id: 'requireLoginPassword'})}
                                                sx={
                                                    {
                                                        "& .MuiInputBase-input.Mui-disabled": {
                                                            WebkitTextFillColor: "#000000",
                                                            background: "#f8f8f8",
                                                        },
                                                        width: '70%'
                                                    }
                                                }
                                            />

                                        </Stack>
                                    </Grid>


                                    <Grid item xs={12} md={12} textAlign="left">
                                        <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                        <Button
                                            variant="contained"
                                            color="success"
                                            type="submit"
                                            aria-label={intl.formatMessage({id: 'submitReply'})}
                                        >
                                            <FormattedMessage id="submitReply" />
                                        </Button>
                                        </ThemeProvider>
                                    </Grid>

                                </Grid>

                        )


                }



            </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>
                        <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={() => setIsWarningPopUp(false)}
                        >
                            OK
                        </Button>
                    </DialogActions>
                </Dialog>
            </div>
        </MainCard>
    );
};

export default FormPanel;
