// material-ui
import {
    Button,
    CardContent, Divider,
    Grid, InputAdornment, TextField, Typography
} from '@mui/material';
import MainCard from "../../components/MainCard";
import {useForm} from "react-hook-form";
//import Radio from '@mui/material/Radio';
//import RadioGroup from '@mui/material/RadioGroup';
//import FormControlLabel from '@mui/material/FormControlLabel';
//import FormControl from '@mui/material/FormControl';
//import {useState} from "react";
import * as React from "react";
import {LIONER_BUTTON_THEME, GENERAL_RED_COLOR} from "../../themes/colorConst";
import {ThemeProvider} from "@emotion/react";
import { useEffect, useState} from "react";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {GET_SETTING_PATH, UPDATE_SETTING_PATH, } from "../../utils/ApiPathConst";
import { getObjectByName, notifySaveSuccess} from "../../utils/CommonFunction";
import LoadingComponent from "../extra-pages/LoadingComponent";
import {SETTING_STRING_DICT} from "../../utils/SettingConst";

import TemplateSettingSection from "./TemplateSettingSection";
import {LIONER_FORM_THEME} from "../../themes/themeConst";

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

const SettingPage = () => {

    //const [notificationType, setNotificationType] = useState(null);

    const { reset, register, handleSubmit } = useForm()
    const [onReady, setOnReady] = useState(false);
    const [errors, setErrors] = useState({});

    const onSubmit = (data) => {
        const formErrors = {};
        if (!data.idleLogoutTime) {
            formErrors.idleLogoutTime = 'Setting value cannot be null';
        }

        if (!data.reminderBefore) {
            formErrors.reminderBefore = 'Setting value cannot be null';
        }

        if (!data.reminderInterval) {
            formErrors.reminderInterval = 'Setting value cannot be null';
        }

        if (!data.reminderLimit) {
            formErrors.reminderLimit = 'Setting value cannot be null';
        }

        if (!data.reminderLimitMaxVal) {
            formErrors.reminderLimitMaxVal = 'Setting value cannot be null';
        }

        if (!data.eventReminderWithin) {
            formErrors.eventReminderWithin = 'Setting value cannot be null';
        }

        if (!data.smtpHost) {
            formErrors.smtpHost = 'Setting value cannot be null';
        }

        if (!data.smtpPort) {
            formErrors.smtpPort = 'Setting value cannot be null';
        }

        if (!data.smtpSenderEmail) {
            formErrors.smtpSenderEmail = 'Setting value cannot be null';
        }

        setErrors(formErrors);

        if (Object.keys(formErrors).length === 0) {
            let tempSettingList =[];
            tempSettingList.push({
                "name": SETTING_STRING_DICT.IDLE_LOGOUT_TIME,
                "value": data.idleLogoutTime
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.REMINDER_BEFORE,
                "value": data.reminderBefore
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.REMINDER_INTERVAL,
                "value": data.reminderInterval
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.REMINDER_LIMIT,
                "value": data.reminderLimit
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.REMINDER_LIMIT_MAX,
                "value": data.reminderLimitMaxVal
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.REMINDER_WITHIN,
                "value": data.eventReminderWithin
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.MAIL_HOST,
                "value": data.smtpHost
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.MAIL_PORT,
                "value": data.smtpPort
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.MAIL_USERNAME,
                "value": data.smtpSenderEmail
            });


            axios.put(`${apiPath}${UPDATE_SETTING_PATH}`,
                {
                    settingList: tempSettingList
                },
            )
                .then((response) => {
                    if (response.status === 204) {
                        notifySaveSuccess();
                    }
                })
                .catch(error => {
                    console.log(error);
                    return false;
                });
        }
        //console.log(notificationType);
    };

    const [refRecord, setRefRecord] = useState([]);

    useEffect(() => {
        getSettingList();
    }, []);

    useEffect(() => {
        if(refRecord.length >0){
            setOnReady(true);
        }
    }, [refRecord]);

    function getSettingList() {
        axios.get(`${apiPath}${GET_SETTING_PATH}`
        )
            .then((response) => {
                if (response.status === 200) {
                    setRefRecord(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function resetForm(){
        //setNotificationType(null);
        reset();
    }
    return (
        !onReady ?
            <LoadingComponent/>
            :
        <Grid container rowSpacing={4.5} columnSpacing={2.75} justifyContent="center">
            <Grid item xs={12} sx={{mb: -2.25}}>
                <Typography variant="h4">System Configuration</Typography>
            </Grid>
            <Grid item xs={12} md={11} lg={10} >
                <MainCard xs={12} md={12} lg={12}
                          border={false}
                          content={false}>

                    <form onSubmit={handleSubmit(onSubmit)}>
                        {/*Title*/}
                        <CardContent sx={{ px: 2.5, pt: 2 }}>
                        </CardContent>

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

                                    <Grid item xs={12} s={12} md={12} lg={5} sx={{ml:3, mr:3, display: 'flex', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            Idle Logout Time
                                        </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">
                                        <TextField
                                            type="number"
                                            fullWidth
                                            error={!!errors.idleLogoutTime}
                                            helperText={errors.idleLogoutTime}
                                            {...register("idleLogoutTime",
                                                {
                                                    value: refRecord === null ? null : getObjectByName(refRecord,SETTING_STRING_DICT.IDLE_LOGOUT_TIME).value,
                                                })}
                                            id="idleLogoutTime"
                                            InputProps={{
                                                endAdornment: <InputAdornment position="start">minutes</InputAdornment>,
                                            }}
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 2*/}
                            <Grid item xs={9} s={12} md={9} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3}}>

                                    <Grid item xs={12} s={12} md={12} lg={5} sx={{ml:3, mr:3, display: 'flex', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            Reminder Before
                                        </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">
                                        <TextField
                                            type="number"
                                            fullWidth
                                            error={!!errors.reminderBefore}
                                            helperText={errors.reminderBefore}
                                            {...register("reminderBefore",
                                                {
                                                    value: refRecord === null ? null : getObjectByName(refRecord,SETTING_STRING_DICT.REMINDER_BEFORE).value,
                                                })}
                                            id='reminderBefore'
                                            InputProps={{
                                                endAdornment: <InputAdornment position="start">days</InputAdornment>,
                                            }}
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 3*/}
                            <Grid item xs={9} s={12} md={9} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3}}>

                                    <Grid item xs={12} s={12} md={12} lg={5} sx={{ml:3, mr:3, display: 'flex', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            Reminder Interval
                                        </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">
                                        <TextField
                                            type="number"
                                            fullWidth
                                            error={!!errors.reminderInterval}
                                            helperText={errors.reminderInterval}
                                            {...register("reminderInterval",
                                                {
                                                    value: refRecord === null ? null : getObjectByName(refRecord,SETTING_STRING_DICT.REMINDER_INTERVAL).value,
                                                })}
                                            id='reminderInterval'
                                            InputProps={{
                                                endAdornment: <InputAdornment position="start">days</InputAdornment>,
                                            }}
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 4*/}
                            <Grid item xs={9} s={12} md={9} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3}}>

                                    <Grid item xs={12} s={12} md={12} lg={5} sx={{ml:3, mr:3, display: 'flex', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            Reminder Limit
                                        </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">
                                        <TextField
                                            type="number"
                                            fullWidth
                                            error={!!errors.reminderLimit}
                                            helperText={errors.reminderLimit}
                                            {...register("reminderLimit",
                                                {
                                                    value: refRecord === null ? null : getObjectByName(refRecord,SETTING_STRING_DICT.REMINDER_LIMIT).value,
                                                })}
                                            id='reminderLimit'
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 5*/}
                            <Grid item xs={9} s={12} md={9} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3}}>

                                    <Grid item xs={12} s={12} md={12} lg={5} sx={{ml:3, mr:3, display: 'flex', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            Reminder Limit: Max. Value
                                        </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">
                                        <TextField
                                            type="number"
                                            fullWidth
                                            error={!!errors.reminderLimitMaxVal}
                                            helperText={errors.reminderLimitMaxVal}
                                            {...register("reminderLimitMaxVal",
                                                {
                                                    value: refRecord === null ? null : getObjectByName(refRecord,SETTING_STRING_DICT.REMINDER_LIMIT_MAX).value,
                                                })}
                                            id='reminderLimitMaxVal'
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 6*/}
                            <Grid item xs={9} s={12} md={12} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3}}>

                                    <Grid item xs={12} s={12} md={12} lg={5} sx={{ml:3, mr:3, display: 'flex', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            Event Reminder Within
                                        </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">
                                        <TextField
                                            type="number"
                                            fullWidth
                                            error={!!errors.eventReminderWithin}
                                            helperText={errors.eventReminderWithin}
                                            {...register("eventReminderWithin",
                                                {
                                                    value: refRecord === null ? null : getObjectByName(refRecord,SETTING_STRING_DICT.REMINDER_WITHIN).value,
                                                })}
                                            id='eventReminderWithin'
                                            InputProps={{
                                                endAdornment: <InputAdornment position="start">years</InputAdornment>,
                                            }}
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 7*/}
                            <Grid item xs={9} s={12} md={12} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3}}>

                                    <Grid item xs={12} s={12} md={12} lg={5} sx={{ml:3, mr:3, display: 'flex', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            SMTP Host
                                        </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">
                                        <TextField
                                            fullWidth
                                            error={!!errors.smtpHost}
                                            helperText={errors.smtpHost}
                                            {...register("smtpHost",
                                                {
                                                    value: refRecord === null ? null : getObjectByName(refRecord,SETTING_STRING_DICT.MAIL_HOST).value,
                                                })}
                                            id='smtpHost'
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 8*/}
                            <Grid item xs={9} s={12} md={12} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3}}>

                                    <Grid item xs={12} s={12} md={12} lg={5} sx={{ml:3, mr:3, display: 'flex', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            SMTP Port
                                        </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">
                                        <TextField
                                            type="number"
                                            fullWidth
                                            error={!!errors.smtpPort}
                                            helperText={errors.smtpPort}
                                            {...register("smtpPort",
                                                {
                                                    value: refRecord === null ? null : getObjectByName(refRecord,SETTING_STRING_DICT.MAIL_PORT).value,
                                                })}
                                            id='smtpPort'
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 6*/}
                            <Grid item xs={9} s={12} md={12} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3}}>

                                    <Grid item xs={12} s={12} md={12} lg={5} sx={{ml:3, mr:3, display: 'flex', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            SMTP Sender Email
                                        </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">
                                        <TextField
                                            fullWidth
                                            error={!!errors.smtpSenderEmail}
                                            helperText={errors.smtpSenderEmail}
                                            {...register("smtpSenderEmail",
                                                {
                                                    value: refRecord === null ? null : getObjectByName(refRecord,SETTING_STRING_DICT.MAIL_USERNAME).value,
                                                })}
                                            id='smtpSenderEmail'
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            </ThemeProvider>
                            <Grid item xs={9} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
                                <MainCard>
                                    <Grid item xs={12} sx={{mb: -2.25}}>
                                        <Typography variant="h5">Email Template Edit</Typography>
                                    </Grid>
                                    <TemplateSettingSection/>
                                </MainCard>
                            </Grid>


                            {/* last row */}
                            <Grid container maxWidth justifyContent="space-between" >
                                <ThemeProvider theme={LIONER_BUTTON_THEME}>
                                    <Grid item>
                                        <Grid container>
                                            <Grid container maxWidth justifyContent="flex-start">
                                                <Grid item sx={{ml:3, mr:3, mb:3}}>
                                                    <Button
                                                        variant="contained"
                                                        type="submit"
                                                        color="save"
                                                    >
                                                        Save
                                                    </Button>
                                                </Grid>

                                                <Grid item sx={{ml:1.5, mr:3, mb:3}}>
                                                    <Button
                                                        variant="contained"
                                                        onClick={resetForm}
                                                        color="cancel"
                                                    >
                                                        Cancel
                                                    </Button>
                                                </Grid>
                                            </Grid>
                                        </Grid>
                                    </Grid>
                                </ThemeProvider>
                            </Grid>
                        </Grid>


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

        </Grid>

    );
};

export default SettingPage;
