// 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_BUTTON_THEME, GENERAL_RED_COLOR} from "../../themes/colorConst";
import {MODULE_COMBO} from "../../utils/ComboConst";
import Autocomplete from "@mui/material/Autocomplete";
import {useContext, useEffect, useState} from "react";
import EventTemplateForm from "./EventTemplateForm";
import axios from "axios";
import {apiPath, getUserData} from "../../auth/utils";
import {
    GET_SEARCH_TEMPLATE_PATH,
    POST_SEARCH_TEMPLATE_PATH, VALIDATE_TEMPLATE_NAME_PATH,
} from "../../utils/ApiPathConst";
import LoadingComponent from "../extra-pages/LoadingComponent";
import {useNavigate, useParams} from "react-router-dom";
import {
    getComboValueByLabel,
    isOptionEqualToValue,
    notifySaveSuccess,
    trimDataBeforePost
} from "../../utils/CommonFunction";
import UploadContext from "../../components/UploadProvider";
import {isObjEmpty} from "../../utils/Utils";
import AwardTemplateForm from "./AwardTemplateForm";
import ApplicationTemplateForm from "./ApplicationTemplateForm";
import {ThemeProvider} from "@emotion/react";

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

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

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

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

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

    const [formData, setFormData] = useState(null);
    const [templateValue, setTemplateValue] = useState(null);
    const [selectedModule, setSelectedModule] = useState(null);
    const [refTemplateData , setRefTemplateData] = useState({});

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

    function validateTemplateName(name, temp) {
        const userData = getUserData();

        axios
            .get(`${apiPath}${VALIDATE_TEMPLATE_NAME_PATH}`, {
                params: {
                    name: name.trim(),
                    userId: userData.id,
                    templateId: params.id,
                    module: selectedModule.label,
                }
            })
            .then((response) => {
                if (response.status === 200) {
                    const formErrors = {};
                    if (response.data.isTaken) {
                        formErrors.name = 'Name have been taken';
                        setErrors(formErrors);
                    } else if (!response.data.isTaken) {
                        if (Object.keys(formErrors).length === 0) {
                            let templateSet={
                                id: params.id,
                                userId: userData.id,
                                name: formData.name.trim(),
                                module: selectedModule.label,
                                criteria: JSON.stringify(temp),
                            }
                            setIsUploading(true);
                            axios.post(`${apiPath}${POST_SEARCH_TEMPLATE_PATH}`,
                                templateSet,
                            )
                                .then((response) => {
                                    if (response.status === 200) {
                                        setIsUploading(false);
                                        notifySaveSuccess();
                                        navigate('/template');
                                    }
                                })
                                .catch(error => {
                                    setIsUploading(false);
                                    console.log(error);
                                    return false;
                                });
                        }
                    }
                }
            })
            .catch((error) => {
                console.log(error);
                return true;
            });
    }

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

    useEffect(() => {
        if(isCollectData && isUserConfirm){
            const formErrors = {};
            if(!selectedModule){
                formErrors.module = "Module is required";
            }

            if (!formData.name || formData.name.trim().length === 0 ) {
                formErrors.name = 'Template name is required';
            }
            setErrors(formErrors);

            if (Object.keys(formErrors).length === 0 && templateValue!== null) {
                let temp={
                    ...formData,
                    ...templateValue
                }
                temp = trimDataBeforePost(temp);
                validateTemplateName(formData.name,temp);
                setIsUploading(false);
                setIsUserConfirm(false);
                setIsCollectData(false);
            }
            else if(Object.keys(formErrors).length >0){
                setTemplateValue(null);
                setIsUploading(false);
                setIsUserConfirm(false);
                setIsCollectData(false);
            }
        }
    }, [templateValue,isCollectData,isUserConfirm]);

    function applyTemplateValue(input){
        setTemplateValue(input);
    }

    const resetForm = () => {
        reset();
        setIsReset(true);
    }

    useEffect(() => {
        if(params.id>0){
            getTemplateData();
        }
    }, []);

    useEffect(() => {
        if(!isObjEmpty(templateData) && !isObjEmpty(refTemplateData)){
            setSelectedModule(getComboValueByLabel(MODULE_COMBO, templateData.module));
            setOnReady(true);
        }
        else if(params.id <0){
            setOnReady(true);
        }
    }, [templateData,refTemplateData]);

    function getTemplateData() {
        axios.get(`${apiPath}${GET_SEARCH_TEMPLATE_PATH}/${params.id}`)
            .then((response) => {
                if (response.status === 200) {
                    setTemplateData(response.data.data);
                    setRefTemplateData(JSON.parse(response.data.data.criteria));
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    useEffect(() => {
        renderByModule();
    }, [selectedModule]);

    const renderByModule = () => {
        if(selectedModule !== null){
            switch (selectedModule.key){
                case 1:
                    return <EventTemplateForm
                        isReset={isReset}
                        register={register}
                        refTemplateData={refTemplateData}
                        templateData={templateData}
                        isCollectData={isCollectData}
                        setValue={setValue}
                        applyTemplateValue={applyTemplateValue}
                        setIsReset={setIsReset}
                        setIsCollectData={setIsCollectData}
                    />
                case 2:
                    return <ApplicationTemplateForm
                        isReset={isReset}
                        register={register}
                        refTemplateData={refTemplateData}
                        templateData={templateData}
                        isCollectData={isCollectData}
                        setValue={setValue}
                        applyTemplateValue={applyTemplateValue}
                        setIsReset={setIsReset}
                        setIsCollectData={setIsCollectData}
                    />
                case 3:
                    return <AwardTemplateForm
                        isReset={isReset}
                        register={register}
                        refTemplateData={refTemplateData}
                        templateData={templateData}
                        isCollectData={isCollectData}
                        setValue={setValue}
                        applyTemplateValue={applyTemplateValue}
                        setIsReset={setIsReset}
                        setIsCollectData={setIsCollectData}
                    />
                default:
                    return "";
            }
        }
    }

    return (
        !onReady ?
            <LoadingComponent/>
            :
        <Grid container rowSpacing={3} columnSpacing={2.75} justifyContent="center">
            <ThemeProvider theme={LIONER_FORM_THEME}>
            <Grid item xs={12} sx={{mt:-1, mb: -2.25}}>
                <Typography variant="h5">Maintain Search Template</Typography>
            </Grid>
            <Grid item xs={12} md={12} lg={12} >
                <MainCard xs={12} md={12} lg={12}
                          content={false}>
                    <form onSubmit={handleSubmit(onSubmit)}>

                        <Grid container alignItems={"center"} justifyContent="left">
                            {/*row 1*/}
                            <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">
                                        Module:
                                        </Typography>
                                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                    </Grid>

                                    <Grid item xs={12} s={12} md={12} lg={3} justifyContent="space-between" alignItems="right">
                                        <Autocomplete
                                            disablePortal
                                            id="module-combo"
                                            size="small"
                                            value={selectedModule === null? null : selectedModule}
                                            options={MODULE_COMBO}
                                            onChange={(event, newValue) => {
                                                setSelectedModule(newValue);
                                            }}
                                            disabled={params.id>0}
                                            isOptionEqualToValue={isOptionEqualToValue}
                                            renderInput={(params) => <TextField
                                                {...params}
                                                error={!!errors.module}
                                                helperText={errors.module}
                                            />}
                                        />
                                    </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 Name:
                                        </Typography>
                                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                    </Grid>

                                    <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                                        <TextField
                                            fullWidth
                                            inputProps={{maxLength: 255}}
                                            {...register("name",{
                                                value: templateData.name,
                                            })}
                                            id="templateName"
                                            error={!!errors.name}
                                            helperText={errors.name}
                                            autoComplete="off"
                                        />
                                    </Grid>
                                </Grid>
                            </Grid>
                            {renderByModule()}

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

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

                                    </Grid>
                                </ThemeProvider>
                            </Grid>
                        </Grid>


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

    );
};

export default MaintainTemplatePage;
