// material-ui
import {
    Grid,
    Typography,
    Stack,
    Box,
    Button
} from '@mui/material';
import * as UrlUtils from "utils/ApiPathConst";
import * as React from "react";
import ForwardIcon from '@mui/icons-material/Forward';

import Loadable from 'components/Loadable';
const LoadingComponent = Loadable(React.lazy(() => import('pages/extra-pages/LoadingComponent')));
const EmailTemplate = Loadable(React.lazy(() => import('pages/EmailTemplate/Detail_GLD/EmailTemplateDetails')))
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
import { useParams } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import { notifyDeleteSuccess, notifySaveSuccess } from 'utils/CommonFunction';
const BackgroundHead = {
    backgroundImage: `url(${titleBackgroundImg})`,
    width: '100%',
    height: '100%',
    backgroundSize: 'contain',
    backgroundRepeat: 'no-repeat',
    backgroundColor: '#0C489E',
    backgroundPosition: 'right'
}

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

const Index = () => {

    const [record, setRecord] = React.useState(null);
    const [onReady, setOnReady] = React.useState(false);
    const params = useParams()
    const navigate = useNavigate()

    React.useLayoutEffect(() => {
        loadForm();
    }, []);

    React.useLayoutEffect(() => {
        if(record !== null || params.id <= 0) setOnReady(true);
    }, [record]);

    const loadForm = () => {
        if (params.id > 0) {
            axios.get(`${UrlUtils.GET_EMAIL}/${params.id}`)
            .then((response) => {
                if (response.status === 200) {
                    // console.log(response)
                    setRecord(response.data.data)
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
        }
        // HttpUtils.get({
        //     url: UrlUtils.GET_EMAIL,
        //     params: {
        //         id: params.id
        //     },
        //     onSuccess: (responseData) => {
        //         setRecord(responseData);
        //     }
        // });
    }

    const onSubmit = (data) => {
        axios.post(`${UrlUtils.POST_EMAIL_SAVE}`,
            {
                id: params.id > 0 ? params.id : null,
                contentChs: data?.contentChs,
                contentCht: data?.contentCht,
                contentEng: data?.contentEng,
                description: data?.description,
                tempKey: data?.tempKey,
                params: data?.params,
                subjectChs: data?.subjectChs,
                subjectCht: data?.subjectCht,
                subjectEng: data?.subjectEng
            }
        ).then((response) => {
            if (response.status === 200) {
                // location.reload();
                navigate('/setting/emailTemplate')
                notifySaveSuccess()
            }
        })
            .catch(error => {
                console.log(error);
                return false;
            });
        // console.log(data)
    }

    const handleDelete = () => {
        axios.delete(`${UrlUtils.DELETE_EMAIL}/${params.id}`,
        )
            .then((response) => {
                // console.log(response)
                if (response.status === 204) {
                    // location.reload();
                    navigate('/setting/emailTemplate');
                    notifyDeleteSuccess()
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    return (
        !onReady ?
            <Grid container sx={{ minHeight: '87vh', mb: 3 }} direction="column" justifyContent="center" alignItems="center">
                <Grid item>
                    <LoadingComponent />
                </Grid>
            </Grid>
            :
            (
                <Grid container sx={{ minHeight: '110vh', backgroundColor: 'backgroundColor.default' }} direction="column" justifyContent="flex-start" alignItems="center" >
                    <Grid item xs={12} width="100%">
                        <div style={BackgroundHead} width="100%">
                            <Stack direction="row" height='70px'>
                                <Typography ml={15} color='#FFF' variant="h4" sx={{ pt: 2 }}>Email Template</Typography>
                            </Stack>
                        </div>
                    </Grid>
                    <Grid item xs={12} width="100%">
                        <Button title="Back" sx={{ ml: 6, mt: 2.5 }} style={{ border: '2px solid' }} variant="outlined" onClick={() => { navigate(-1) }}>
                            <ForwardIcon style={{ height: 30, width: 50, transform: "rotate(180deg)" }} />
                        </Button>
                    </Grid>
                    {/*row 1*/}

                    <Grid item xs={12} md={12} width="100%">
                        <Grid item xs={12} md={12} sx={{ pt: 2, ml: 6, mr: 6, mb: 6}}>
                            <Box xs={12} md={12} sx={{ p: 4, borderRadius: '10px', backgroundColor: '#ffffff' }}>
                                <EmailTemplate
                                    formData={record}
                                    _onSubmit={onSubmit}
                                    handleDelete={handleDelete}
                                />
                            </Box>
                        </Grid>
                    </Grid>
                    {/*row 2*/}
                </Grid >
            )
    );
};

export default Index;