// material-ui
import {
    Button,
    Grid, TextField, Typography
} from '@mui/material';
import MainCard from "../../components/MainCard";
import {useForm} from "react-hook-form";
import * as React from "react";
import {LIONER_LONG_BUTTON_THEME, GENERAL_RED_COLOR} from "../../themes/colorConst";
import {EMAIL_TEMPLATE_COMBO} from "../../utils/ComboConst";
import Autocomplete from "@mui/material/Autocomplete";
import {useContext, useEffect, useState} from "react";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {
    GET_SETTING_ROUTE, POST_TODO_TEST, UPDATE_SETTING_PATH,
} from "../../utils/ApiPathConst";
import LoadingComponent from "../extra-pages/LoadingComponent";
import {useParams} from "react-router-dom";
import {/*getComboValueByLabel,*/
    isOptionEqualToValue,
    notifySaveSuccess,
    notifySendSuccess
} from "../../utils/CommonFunction";
import UploadContext from "../../components/UploadProvider";
//import {isObjEmpty} from "../../utils/Utils";
import {ThemeProvider} from "@emotion/react";

import {LIONER_FORM_THEME} from "../../themes/themeConst";
import {isObjEmpty} from "../../utils/Utils";

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

const TemplateSettingSection = () => {
    const params = useParams();
    const [errors, setErrors] = useState({});

    const { register, setValue, getValues } = useForm()
    const [onReady, setOnReady] = useState(false);
    const { setIsUploading } = useContext(UploadContext);

    const [isCollectData, setIsCollectData] = useState(false);
    const [isUserConfirm, setIsUserConfirm] = useState(false);

    const [formData, setFormData] = useState(null);
    const [selectedTemplate, setSelectedTemplate] = useState(null);

    const [templateData, setTemplateData] = useState({});
    const [isEdited, setIsEdited] = useState(false);

    const onUpload = () => {
        const data = getValues();
        setFormData(data);
        setIsUserConfirm(true);
        setIsCollectData(!isCollectData);
    };

    useEffect(() => {
        if(isCollectData && isUserConfirm){

            const formErrors = {};

            if(selectedTemplate === null){
                formErrors.selectedTemplate = 'Email Template cannot be null';
            }

            if (!formData.template ) {
                formErrors.template = 'Template cannot be null';
            }

            setErrors(formErrors);

            if (Object.keys(formErrors).length === 0) {
                let tempSettingList =[];

                tempSettingList.push({
                    "name": selectedTemplate.value,
                    "value": formData.template
                });
                setIsUploading(true);
                axios.put(`${apiPath}${UPDATE_SETTING_PATH}`,
                    {
                        settingList: tempSettingList
                    },
                )
                    .then((response) => {
                        if (response.status === 204) {
                            setIsEdited(false);
                            setIsUploading(false);
                            notifySaveSuccess();
                        }
                    })
                    .catch(error => {
                        setIsUploading(false);
                        console.log(error);
                        return false;
                    });
            }
        }
        setIsUserConfirm(false);
        setIsCollectData(false);
    }, [formData]);

    // const resetForm = () => {
    //     reset();
    //     setSelectedTemplate(null);
    // }

    const testEmailTemplate = () => {
        const formData = getValues();
        const formErrors = {};

        if(selectedTemplate === null){
            formErrors.selectedTemplate = 'Email Template cannot be null';
        }

        if (!formData.emailTo ) {
            formErrors.emailTo = 'Receiver cannot be null';
        }

        setErrors(formErrors);

        if (Object.keys(formErrors).length === 0) {
            setIsUploading(true);
            axios.get(`${apiPath}${POST_TODO_TEST}`,
                {
                    params:{
                        templateName: selectedTemplate.value,
                        receiver: formData.emailTo
                    }
                },
            )
                .then((response) => {
                    if (response.status === 200) {
                        setIsEdited(false);
                        setIsUploading(false);
                        notifySendSuccess();
                    }
                })
                .catch(error => {
                    setIsUploading(false);
                    console.log(error);
                    return false;
                });
        }

    }

    useEffect(() => {
        setOnReady(true);
    }, [templateData]);

    function getTemplateData() {
        if(!isObjEmpty(selectedTemplate)){
            axios.get(`${apiPath}${GET_SETTING_ROUTE}/${selectedTemplate.value}`)
                .then((response) => {
                    if (response.status === 200) {
                        setTemplateData(response.data.data);
                        setValue("template", response.data.data);

                    }
                })
                .catch(error => {
                    console.log(error);
                    return false;
                });
        }
    }

    useEffect(() => {
        getTemplateData();
    }, [selectedTemplate]);

    return (
        !onReady ?
            <LoadingComponent/>
            :
        <Grid container rowSpacing={4.5} columnSpacing={2.75} justifyContent="center">
            <Grid item xs={12} md={12} lg={12} >
                <MainCard xs={12} md={12} lg={12}
                          border={false}
                          content={false}>
                    <form>

                        <Grid container alignItems={"center"} justifyContent="left">
                            {/*row 1*/}
                            <ThemeProvider theme={LIONER_FORM_THEME}>
                            <Grid item xs={6} s={12} md={12} lg={12} sx={{mt:3, ml:3, mr:3, mb:3}}>
                                <Grid container>

                                    <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            Email Template:
                                        </Typography>
                                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                    </Grid>

                                    <Grid item xs={12} s={12} md={12} lg={5} justifyContent="space-between" alignItems="right">
                                        <Autocomplete
                                            disablePortal
                                            id="module-combo"
                                            size="small"
                                            value={selectedTemplate === null? null : selectedTemplate}
                                            options={EMAIL_TEMPLATE_COMBO}
                                            onChange={(event, newValue) => {
                                                setSelectedTemplate(newValue);
                                            }}
                                            disabled={params.id>0}
                                            isOptionEqualToValue={isOptionEqualToValue}
                                            renderInput={(params) => <TextField
                                                {...params}
                                                error={!!errors.selectedTemplate}
                                                helperText={errors.selectedTemplate}
                                            />}
                                        />
                                    </Grid>
                                </Grid>
                            </Grid>

                            <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container>
                                    <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            Template Detail:
                                        </Typography>
                                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                    </Grid>
                                </Grid>
                            </Grid>
                            </ThemeProvider>

                            <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container>
                                    <Grid item xs={12} s={12} md={12} lg={12} justifyContent="space-between" alignItems="right">
                                        <TextField
                                            fullWidth
                                            inputProps={{style: {fontSize: '1.1rem'}}}
                                            {...register("template",{
                                                value: templateData.template,
                                            })}
                                            onChange={() => {
                                                if(!isEdited){
                                                    setIsEdited(true);
                                                }
                                            }}
                                            multiline
                                            maxRows={30}
                                            id="templateName"
                                            error={!!errors.template}
                                            helperText={errors.template}
                                        />
                                    </Grid>
                                </Grid>
                            </Grid>

                            <Grid item s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}} alignItems={"center"} justifyContent="center">
                                <ThemeProvider theme={LIONER_LONG_BUTTON_THEME}>
                                    <Grid container maxWidth justifyContent="space-between">
                                        <Grid item lg={3.5} sx={{mr:1.5}}>
                                            <Button
                                                size="medium"
                                                variant="contained"
                                                onClick={onUpload}
                                                color="save">
                                                Save Template
                                            </Button>
                                        </Grid>

                                        <Grid item lg={8}>
                                            <Grid container maxWidth justifyContent="flex-end">
                                                <ThemeProvider theme={LIONER_FORM_THEME}>
                                                    <Grid item s={8} md={8} lg={4} sx={{ml:3, mr:1.5}}>
                                                        <TextField
                                                            size="small"
                                                            fullWidth
                                                            {...register("emailTo")}
                                                            id="templateName"
                                                            error={!!errors.emailTo}
                                                            helperText={errors.emailTo}
                                                            label="Send To"
                                                        />
                                                    </Grid>
                                                </ThemeProvider>

                                                <Grid item sx={{ml:1.5}}>
                                                    <Button
                                                        sx={{
                                                            width: "600px"
                                                        }}
                                                        size="medium"
                                                        variant="contained"
                                                        color="save"
                                                        disabled={isEdited}
                                                        onClick={testEmailTemplate}>
                                                        Test Template
                                                    </Button>
                                                </Grid>

                                            </Grid>
                                        </Grid>

                                    </Grid>
                                </ThemeProvider>
                            </Grid>
                        </Grid>
                    </form>
                </MainCard>
            </Grid>

        </Grid>

    );
};

export default TemplateSettingSection;
