import {
    Dialog, DialogTitle, DialogContent, DialogActions,
    Typography,
    Autocomplete,
    CardContent,
    Grid,
    Stack,
    TextField,
    FormLabel,
    Button
} from '@mui/material';

import * as UrlUtils from "utils/ApiPathConst";
import * as HttpUtils from "utils/HttpUtils";
import * as DateUtils from "utils/DateUtils"

import MainCard from "components/MainCard";
import * as ComboData from "utils/ComboData";
import * as React from "react";
import { useFormik } from 'formik';
import { useNavigate } from "react-router-dom";
import { useIntl } from 'react-intl';
import Loadable from 'components/Loadable';
import { notifySaveSuccess } from 'utils/CommonFunction';
const UploadFileTable = Loadable(React.lazy(() => import('./UploadFileTable')));

/** Keeps Formik fields defined so inputs stay controlled before API data loads. */
const proofFormInitialValues = {
    reviseDeadline: '',
    proofPaymentDeadline: '',
    length: '',
    noOfPages: '',
    fee: '',
    groupType: ''
};

const FormPanel = ({ formData }) => {
    const intl = useIntl();
    const [data, setData] = React.useState({});
    const [columnPrice, setColumnPrice] = React.useState(ComboData.proofPrice[0]);
    const [attachments, setAttachments] = React.useState([]);

    const [checkCode, setCheckCode] = React.useState("");
    const [expectedCode, setExpectedCode] = React.useState("");

    const [wait, setWait] = React.useState(false);

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

    const [saving, setSaving] = React.useState(false);

    const [proofPaymentDeadlineMin, setProofPaymentDeadlineMin] = React.useState({});
    const [reviseDeadlineMin, setReviseDeadlineMin] = React.useState({});
    const fileInputRef = React.useRef(null);

    const navigate = useNavigate()

    React.useEffect(() => {
        if (formData) {
            setData(formData);
            if (formData.groupType == "Private Bill") {
                setColumnPrice(ComboData.proofPrice[1])
                formData['length'] = 18;
            }
            setProofPaymentDeadlineMin(formData.proofPaymentDeadline);
            setReviseDeadlineMin(formData.reviseDeadline);
            setExpectedCode(formData.groupNo.substr(1,formData.groupNo.length)+"-"+formData.issueNo+"-"+formData.issueYear.toString().substr(2, formData.issueYear.toString().length));
        }
    }, [formData]);


    React.useEffect(() => {
        if (!attachments || attachments.length <= 0) {
            formik.setFieldValue("length", 0);
            formik.setFieldValue("noOfPages", 0);
            formik.setFieldValue("fee", 0);
            return;
        }

        doCalculate();

    }, [attachments]);

    const doCalculate = () => {
        setWait(true);
        if (!attachments || attachments.length <= 0) {
            setWarningText("Unable to calculate, please upload a valid document.");
            setIsWarningPopUp(true);
            setWait(false);
            return;
        }
        HttpUtils.postWithFiles({
            url: UrlUtils.PROOF_CHECK_PRICE,
            params: {
                appId: data.id,
            },
            files: attachments,
            onSuccess: function (responseData) {
                if (responseData.data.detail) {
                    setWarningText("Unable to calculate, please upload a valid document or input manually.");
                    setIsWarningPopUp(true);
                    setWait(false);
                    return;
                }
                formik.setFieldValue("length", responseData.data.length);
                let colValue = 0;
                setColumnPrice(ComboData.proofPrice.find(obj => {
                    colValue = obj.value;
                    return obj.colCount === responseData.data.column
                }));
                formik.setFieldValue("noOfPages", responseData.data.total_no_of_page);
                formik.setFieldValue("fee", (data.groupType == "Private Bill" ? 6552 * responseData.data.total_no_of_page : responseData.data.length * colValue));
                if (data.groupType == "Private Bill" && responseData.data.file.length > 0) {
                    let attachmentList = attachments;
                    for (let i = 0; i < responseData.data.file.length; i++) {
                        let file = responseData.data.file[i];
                        attachmentList.find(item => item.name == file.filename)["no_of_page"] = file.no_of_page;
                    }
                    setAttachments(attachmentList);
                }
                setCheckCode(responseData.data.check_code);
                setWait(false);
            },
            onError: function () {
                // console.log(error)
                setWarningText("Unable to calculate, please input manually.");
                setIsWarningPopUp(true);
                setWait(false);
            }
        });
    }

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: { ...proofFormInitialValues, ...data },
        onSubmit: values => {
            setSaving(true);
            if (!attachments || attachments.length <= 0) {
                setWarningText("Please upload file.");
                setIsWarningPopUp(true);
                setSaving(false);
                return;
            }

            if (!values.length|| values.length <= 0) {
                setWarningText("Column should > 0");
                setIsWarningPopUp(true);
                setSaving(false);
                return;
            }
            if(formik.values.groupType == "Private Bill" ){
                if (!values.noOfPages || values.noOfPages <= 0) {
                    setWarningText("Page should > 0");
                    setIsWarningPopUp(true);
                    setSaving(false);
                    return;
                }    
            }
            // console.log(values);
            HttpUtils.postWithFiles({
                url: UrlUtils.CREATE_PROOF,
                params: {
                    appId: values.id,
                    fee: values.fee,
                    length: values.length,
                    colCount: columnPrice.colCount,
                    noOfPages: values.noOfPages,
                    reviseDeadline: DateUtils.convertToDate(values.reviseDeadline).getTime(),
                    proofPaymentDeadline: DateUtils.convertToDate(values.proofPaymentDeadline).getTime()
                },
                files: attachments,
                onSuccess: function (responeData) {
                    if (responeData.success == true) {
                        notifySaveSuccess()
                        navigate("/proof/search");
                    } else {
                        let msg = responeData.msg;
                        if (msg === "haveActiveProof") {
                            msg = "Action Failed: There is already a pending payment and proofreading record for client review."
                        } else if (msg === "haveProofed") {
                            msg = "Action Failed: An active proof is already created for this application."
                        } else {
                            msg = intl.formatMessage({ id: msg });
                        }
                        setWarningText(msg);
                        setIsWarningPopUp(true);
                    }

                }
            });
        }
    });

    const readFile = (event) => {
        let file = event.target.files && event.target.files[0];
        if (file) {
            if (!file.name.toLowerCase().substr(file.name.length - 4).includes(".pdf")) {
                setWarningText("Please upload a valid file (File format: .pdf).");
                setIsWarningPopUp(true);
                event.target.value = "";
                return;
            }
            if (file.size >= (10 * 1024 * 1034)) {
                setWarningText("The file size for uploading should be less than 10MB");
                setIsWarningPopUp(true);
                event.target.value = "";
                return;
            }
            file['id'] = attachments.length;
            setAttachments([
                ...attachments,
                file
            ]);
            event.target.value = "";
        }
    }

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

            <form onSubmit={formik.handleSubmit}>
                {/*row 1*/}
                <CardContent sx={{ px: 2.5, pt: 3 }}>
                    <Grid item justifyContent="space-between" alignItems="center">
                        <Typography variant="h4" sx={{ mb: 2, borderBottom: "1px solid black" }}>
                            Proof
                        </Typography>
                    </Grid>
                </CardContent>

                {/*row 2*/}
                <Grid container direction="column" sx={{ paddingLeft: 4, paddingRight: 4 }} spacing={1}>

                    <Grid item xs={12} md={12}>
                        <Stack direction="row" sx={{ display: 'flex', alignItems: 'center' }}>
                            <FormLabel sx={{ paddingRight: 2, textAlign: "center" }}>
                                <Typography variant="h5">Deadline for online manuscript revision:</Typography>
                            </FormLabel>
                            <TextField
                                fullWidth
                                size="small"
                                type="datetime-local"
                                onChange={formik.handleChange}
                                name="reviseDeadline"
                                value={formik.values["reviseDeadline"]}
                                InputProps={{ inputProps: { min: DateUtils.datetimeStr(reviseDeadlineMin) } }}
                                variant="outlined"
                                sx={
                                    {
                                        "& .MuiInputBase-input.Mui-disabled": {
                                            WebkitTextFillColor: "#000000",
                                            background: "#f8f8f8",
                                        },
                                        width: '30%'
                                    }
                                }
                            />
                        </Stack>
                    </Grid>

                    <Grid item xs={12} md={12}>
                        <Stack direction="row" sx={{ display: 'flex', alignItems: 'center' }}>
                            <FormLabel sx={{ paddingRight: 2, textAlign: "center" }}>
                                <Typography variant="h5">Deadline for online confirm proof:</Typography>
                            </FormLabel>
                            <TextField
                                fullWidth
                                size="small"
                                type="datetime-local"
                                onChange={formik.handleChange}
                                name="proofPaymentDeadline"
                                value={formik.values["proofPaymentDeadline"]}
                                InputProps={{ inputProps: { min: DateUtils.datetimeStr(proofPaymentDeadlineMin) } }}
                                variant="outlined"
                                sx={
                                    {
                                        "& .MuiInputBase-input.Mui-disabled": {
                                            WebkitTextFillColor: "#000000",
                                            background: "#f8f8f8",
                                        },
                                        width: '30%'
                                    }
                                }
                            />
                        </Stack>
                    </Grid>
                    <Grid item xs={12} md={12}>
                        <Button
                            variant="contained"
                            size="large"
                            disabled={attachments.length >= (formik.values.groupType == "Private Bill" ? 2 : 1)}
                            type="button"
                            onClick={() => {
                                if (fileInputRef.current) {
                                    fileInputRef.current.click();
                                }
                            }}
                            onKeyDown={(event) => {
                                if (event.key === 'Enter' || event.key === ' ') {
                                    event.preventDefault();
                                    if (fileInputRef.current) {
                                        fileInputRef.current.click();
                                    }
                                }
                            }}
                        >
                            <Typography variant="h5">Upload Files</Typography>
                        </Button>
                        <input
                            id="uploadFileBtn"
                            name="file"
                            type="file"
                            accept=".pdf"
                            hidden
                            disabled={attachments.length >= (formik.values.groupType == "Private Bill" ? 2 : 1)}
                            onChange={readFile}
                            aria-label={intl.formatMessage({ id: 'ariaUploadPdfFile' })}
                            ref={fileInputRef}
                        />
                    </Grid>
                    <Grid item xs={12} md={12}>
                        <UploadFileTable
                            key="uploadTable"
                            recordList={attachments}
                            setRecordList={setAttachments}
                            showPageColumn={formik.values.groupType == "Private Bill"}
                            _checkCode={checkCode}
                            _expectedCode={expectedCode}
                        />
                    </Grid>

                    {
                        wait ?
                            <Grid item xs={12} md={12} sx={{ mt: 1.5, mb: 1.5 }}>
                                <Typography variant="h3" style={{ color: "blue" }}>Calculating, please wait ...</Typography>
                            </Grid>
                            :
                            <Grid item xs={12} md={12}>
                                <Button
                                    size="large"
                                    variant="contained"
                                    onClick={doCalculate}
                                    sx={{
                                        textTransform: 'capitalize',
                                        alignItems: 'end'
                                    }}>
                                    <Typography variant="h5">Calculate</Typography>
                                </Button>
                            </Grid>
                    }



                    {
                        formik.values.groupType == "Private Bill" ?
                            <Grid item xs={12} md={12}>
                                <Stack direction="row" sx={{ display: 'flex', alignItems: 'center' }}>
                                    <TextField
                                        fullWidth
                                        size="small"
                                        type="number"
                                        value={formik.values["noOfPages"]}
                                        onChange={(event) => {
                                            const value = parseInt(event.target.value);
                                            formik.setFieldValue("noOfPages", value);
                                            formik.setFieldValue("fee", 6552 * value);
                                        }}
                                        variant="outlined"
                                        sx={
                                            {
                                                "& .MuiInputBase-input.Mui-disabled": {
                                                    WebkitTextFillColor: "#000000",
                                                    background: "#f8f8f8",
                                                },
                                                width: '15%'
                                            }
                                        }
                                    />
                                    <FormLabel sx={{ paddingLeft: 2, paddingRight: 2, textAlign: "center" }}>
                                        <Typography variant="h5">pages</Typography>
                                    </FormLabel>
                                    <FormLabel sx={{ paddingLeft: 2, paddingRight: 2, textAlign: "center" }}>
                                        <Typography variant="h5">x</Typography>
                                    </FormLabel>
                                    <FormLabel sx={{ paddingLeft: 2, paddingRight: 2, textAlign: "center" }}>
                                        <Typography variant="h5">${formik.values.price ? formik.values.price : "6,552"}</Typography>
                                    </FormLabel>
                                </Stack>
                            </Grid>
                            :
                            <Grid item xs={12} md={12}>
                                <Stack direction="row" sx={{ display: 'flex', alignItems: 'center' }}>
                                    <TextField
                                        fullWidth
                                        size="small"
                                        type="number"
                                        onChange={(event) => {
                                            let value = parseInt(event.target.value);
                                            formik.setFieldValue("length", value);
                                            formik.setFieldValue("fee", columnPrice.value * value);
                                        }}
                                        name="length"
                                        value={formik.values["length"]}
                                        variant="outlined"
                                        sx={
                                            {
                                                "& .MuiInputBase-input.Mui-disabled": {
                                                    WebkitTextFillColor: "#000000",
                                                    background: "#f8f8f8",
                                                },
                                                width: '15%'
                                            }
                                        }
                                    />
                                    <FormLabel sx={{ paddingLeft: 2, paddingRight: 2, textAlign: "center" }}>
                                        <Typography variant="h5">cm</Typography>
                                    </FormLabel>

                                    <FormLabel sx={{ paddingLeft: 2, paddingRight: 4, textAlign: "center" }}>
                                        <Typography variant="h5">x</Typography>
                                    </FormLabel>

                                    <Autocomplete
                                        sx={{
                                            width: "15%",
                                            '& .MuiInputBase-root': { alignItems: 'center' },
                                            '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                            '& .MuiOutlinedInput-root': { height: 40 }
                                        }}
                                        disablePortal
                                        id="price"
                                        options={ComboData.proofPrice}
                                        value={columnPrice}
                                        inputValue={(columnPrice?.label) ? columnPrice?.label : ""}
                                        getOptionLabel={(option) =>
                                            option != null && option.label != null ? String(option.label) : ""
                                        }
                                        onChange={(event, newValue) => {
                                            setColumnPrice(newValue)
                                            formik.values["fee"] = newValue.value * formik.values.length;
                                        }}
                                        
                                        renderInput={(params) => (
                                            <TextField {...params}
                                                InputLabelProps={{
                                                    shrink: true
                                                }}
                                                sx={{
                                                    width: "100%"
                                                }}
                                            />
                                        )}
                                    />
                                </Stack>
                            </Grid>
                    }





                    <Grid item xs={12} md={12}>
                        <Stack direction="row" sx={{ display: 'flex', alignItems: 'center' }}>
                            <FormLabel sx={{ paddingRight: 2, textAlign: "center" }}>
                                <Typography variant="h5">Necessary fee:</Typography>
                            </FormLabel>
                            <FormLabel sx={{ paddingLeft: 2, paddingRight: 2, textAlign: "center" }}>
                                <Typography variant="h5">$</Typography>
                            </FormLabel>
                            <TextField
                                fullWidth
                                size="small"
                                type="text"
                                onChange={formik.handleChange}
                                name="fee"
                                value={formik.values["fee"]}
                                variant="outlined"
                                sx={
                                    {
                                        "& .MuiInputBase-input.Mui-disabled": {
                                            WebkitTextFillColor: "#000000",
                                            background: "#f8f8f8",
                                        },
                                        width: '15%'
                                    }
                                }
                            />

                        </Stack>
                    </Grid>


                    <Grid item xs={12} md={12}>
                        <Button
                            size="large"
                            variant="contained"
                            color="success"
                            type="submit"
                            disabled={saving}
                            sx={{
                                textTransform: 'capitalize',
                                alignItems: 'end'
                            }}>
                            <Typography variant="h5">Save</Typography>
                        </Button>
                    </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><Typography variant="h3">Warning</Typography></DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h4" style={{ padding: '16px' }}>{warningText}</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => setIsWarningPopUp(false)}><Typography variant="h5">OK</Typography></Button>
                    </DialogActions>
                </Dialog>
            </div>
            <div>
                <Dialog
                    open={wait}
                    onClose={() => setWait(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h4" style={{ padding: '16px' }}>Calculating, please wait ...</Typography>
                    </DialogContent>
                </Dialog>
            </div>
        </MainCard>
    );
};

export default FormPanel;
