// material-ui
import {
    Button,
    FormControlLabel,
    Grid, InputAdornment, Switch, TextField, Typography
} from '@mui/material';
import MainCard from "../../../components/MainCard";
import * as React from "react";
import {useForm} from "react-hook-form";
import {useContext, useEffect, useState} from "react";
import LoadingComponent from "../../extra-pages/LoadingComponent";
import {useLocation, useNavigate, useParams} from "react-router-dom";
import {
    GeneralConfirmWindow,
    getComboValueByIdList,
    getComboValueByLabel,
    getDateString,
    getDeletedRecordWithRefList,
    getIdList,
    getNewRecordWithRefList, isOptionEqualToValue, isStringEmptyAfterTrim, notifyDeleteError, notifyDeleteSuccess,
    notifySaveSuccess, trimDataBeforePost,
} from "../../../utils/CommonFunction";
import axios from "axios";
import {apiPath} from "../../../auth/utils";
import {
    CHECK_EVENT_DUPLICATE, //GET_EVENT_NOTIFICATION_OVERTIME,
    GET_CONSULTANT_PATH,
    GET_SUB_DIVISION_COMBO_LIST,
    POST_CONSULTANT_PATH
} from "../../../utils/ApiPathConst";
import {LIONER_BUTTON_THEME, LIONER_LONG_BUTTON_THEME, GENERAL_RED_COLOR} from "../../../themes/colorConst";
import dayjs from "dayjs";
import {ThemeProvider} from "@emotion/react";
import UploadContext from "../../../components/UploadProvider";
import {isObjEmpty} from "../../../utils/Utils";
import AbilityContext from "../../../components/AbilityProvider";
import {CARD_MAX_WIDTH} from "../../../themes/themeConst";

const ConsultantForm = ({   refConsultantDetail,
                       isNewRecord,
                       getConsultantDetail,
}) => {
    const location = useLocation();
    const queryParams = new URLSearchParams(location.search);
    const id = queryParams.get("id");
   
    const params = useParams();
    const navigate = useNavigate();
    const ability = useContext(AbilityContext);
    const [onReady, setOnReady] = useState(false);
    const [errors, setErrors] = useState({});
    const [consultantDetail, setConsultantDetail] = useState({});
    const [isCollectData, setIsCollectData] = useState(false);
    const [userConfirm, setUserConfirm] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const { setIsUploading } = useContext(UploadContext);
    const [refConsultant, setRefConsultant] = useState({});

    //form data
    const {register, getValues, setValue} = useForm();
    
    const [isWindowOpen, setIsWindowOpen] = React.useState(false);

    const handleClose = () => {
        setIsWindowOpen(false);
    };

    const handleDeleteClick = () => {
        setIsWindowOpen(true);
    };

    function updateData(){
        axios.delete(`${apiPath}${GET_CONSULTANT_PATH}/${params.id}`,
        )
            .then((response) => {
                if (response.status === 204) {
                    notifyDeleteSuccess();
                    setIsWindowOpen(false);
                    returnSearchPage();
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
        // }

    }

    useEffect(()=>{
        if (!isNewRecord) {
            setRefConsultant(refConsultantDetail);
        }        
    },[]);

    useEffect(()=>{
        //if ref data ready
        if (!isObjEmpty(refConsultant)) {
            //checkOvertime();
            alert(id + " " + refConsultant.id);
            if(refConsultant.id !== null){
                setValue("name", refConsultant.name);
            }
            setDob(dayjs(getDateString(refConsultant.dob)));
        }
    },[refConsultant]);

    useEffect(()=>{
        if(!isObjEmpty(refConsultant)) {
            setOnReady(true);
        }
        else if(isNewRecord){
            setOnReady(true);
            setIsEditing(true);
        }
    },[refConsultant]);
    
    useEffect(() => {
        //upload latest data to parent
        if(isCollectData){
            const values = getValues();
            const formErrors = {};

            if (isStringEmptyAfterTrim(values.name)) {
                formErrors.name = 'Last Name is required';
            }
           
            setErrors(formErrors);
            
            if (Object.keys(formErrors).length === 0) {
                let data = {};
                data["name"] = values.name;
                //data["id"] = values.id;
                
                setConsultantDetail(data);
            }
            else if(isCollectData){
                setUserConfirm(false);
                setIsCollectData(false);
            }
            // setUserConfirm(false);
            // setIsCollectData(false);
        }
    }, [isCollectData]);

    function returnSearchPage(){
        navigate('/consultant');
    }

    useEffect(() => {
        if (userConfirm) {
            postConsultant();
        }
        setUserConfirm(false);
    }, [consultantDetail]);


    const submitData = () => {
        setIsCollectData(!isCollectData);
        setUserConfirm(true);
    }

    const updateIsEdit = () => {
        setIsEditing(!isEditing);
    }

    function postConsultant(){
        setIsUploading(true);
        const temp = trimDataBeforePost(consultantDetail);
        axios.post(`${apiPath}${POST_CONSULTANT_PATH}`,
            temp,
        )
            .then((response) => {
                if (response.status === 200) {
                    notifySaveSuccess();
                    if(isNewRecord){
                        setIsUploading(false);
                        navigate('/consultant')
                    }
                    else{
                        setIsUploading(false);
                        getConsultantDetail(params.id);
                        //checkOvertime();
                        setIsEditing(!isEditing);
                    }
                    setIsCollectData(!isCollectData);

                }
            })
            .catch(error => {
                if (error.response.status === 422){
                    const formErrors = {};
                    formErrors.subDivision = error.response.data.error;
                    setErrors(formErrors);
                }
                console.log(error);
                setIsUploading(false);
                return false;
            });
    }

    return (
        !onReady ?
            <LoadingComponent/>
            :
            <MainCard
                      content={false}
                      sx={{width:CARD_MAX_WIDTH}}
            >

                <form>
                    <Grid container>                       
                        
                        <Grid item xs={12} s={12} md={12} lg={5.5} sx={{ml: 3, mr: 3, mb: 3, mt:1}}>
                            <Grid container alignItems={"flex-start"}>
                                <Grid item xs={4} s={4} md={4} lg={1.5}
                                      sx={{ml: 3, mr: 3, mt:1, display: 'flex', alignItems: 'flex-start'}}>
                                    <Typography variant="lionerSize" component="span">
                                        Name:
                                    </Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={7}>
                                    <TextField
                                        fullWidth
                                        {...register("name",
                                            {
                                                value: refConsultant.name,
                                            })}
                                        id='name'
                                        required
                                        disabled={!isEditing}
                                        inputProps={{maxLength: 500, style: {fontSize: '1.1rem'}}}
                                        InputProps={{
                                            style: { minHeight:'42.5px', maxHeight: '50vh' },
                                        }}
                                        multiline
                                        maxRows={10}
                                        autoComplete="off"
                                    />
                                </Grid>
                            </Grid>

                            {/*row 2*/}
                            {
                                (isEditing ) ?
                                    <Grid container maxWidth justifyContent="space-between">
                                        <ThemeProvider theme={LIONER_BUTTON_THEME}>
                                            <Grid item>
                                                <Grid container>
                                                    <Grid item sx={{ml:{xs:1.5,md:1.5,lg:1.5}, mr:1.5, mb:1, mt:2}}>
                                                        <Button
                                                            variant="contained"
                                                            color="save"
                                                            onClick={submitData}
                                                        >
                                                            Save
                                                        </Button>
                                                    </Grid>
                                                    <Grid item sx={{ml:1.5, mr:1.5, mb:1, mt:2}}>
                                                        <Button
                                                            variant="contained"
                                                            color="cancel"
                                                            onClick={isNewRecord? returnSearchPage : updateIsEdit}
                                                        >
                                                            Cancel
                                                        </Button>

                                                    </Grid>
                                                    <Grid item sx={{ml:{xs:1.5,md:1.5,lg:1.5}, mr:3, mb:1, mt:2}}>
                                                        {!isNewRecord && (<Button
                                                            variant="contained"
                                                            color="delete"
                                                            disabled={!ability.can('MAINTAIN','CONSULTANT')}
                                                            onClick={handleDeleteClick}
                                                        >
                                                            Delete
                                                        </Button>
                                                        )}
                                                        <GeneralConfirmWindow
                                                            isWindowOpen={isWindowOpen}
                                                            title={"Attention"}
                                                            //content={`Confirm to delete Event "${consultantDetail.name}" ?`}
                                                            content={`Are you sure to delete this consultant?`}
                                                            onNormalClose={handleClose}
                                                            onConfirmClose={updateData}
                                                        />
                                                    </Grid>
                                                </Grid>
                                            </Grid>
                                            <Grid item>
                                                <Grid container>
                                                    <ThemeProvider theme={LIONER_LONG_BUTTON_THEME}>

                                                    {/* <Grid item sx={{ml:{xs:1.5,md:1.5,lg:3}, mb:1, mt:2}}>
                                                        <Button
                                                            variant="contained"
                                                            color="saveAs"
                                                            // onClick={copyEventAsNew}
                                                            disabled={isNewRecord}
                                                        >
                                                            Copy as new
                                                        </Button>
                                                    </Grid> */}

                                                    {/* <Grid item sx={{ml:{xs:1.5,md:1.5,lg:3}, mb:1, mt:2}}>
                                                        <Button
                                                            variant="contained"
                                                            color="create"
                                                            onClick={createNewApplication}
                                                            disabled={isNewRecord}
                                                        >
                                                            New Application
                                                        </Button>
                                                    </Grid> */}
                                                    </ThemeProvider>
                                                </Grid>
                                            </Grid>
                                        </ThemeProvider>
                                    </Grid>
                                    :
                                    <Grid container maxWidth justifyContent="space-between" sx={{ml:2, mr:2}}>
                                        <ThemeProvider theme={LIONER_BUTTON_THEME}>
                                            <Grid item>
                                                <Grid container>
                                                    <Grid item sx={{ml:1, mr:3, mb:1, mt:2}}>
                                                        <Button
                                                            variant="contained"
                                                            color="save"
                                                            onClick={updateIsEdit}
                                                            disabled={!ability.can('MAINTAIN','CONSULTANT')}
                                                        >
                                                            Edit
                                                        </Button>
                                                    </Grid>
                                                    <Grid item sx={{ml:1, mr:3, mb:1, mt:2}}>
                                                        <Button
                                                            variant="contained"
                                                            color="cancel"
                                                            onClick={returnSearchPage}
                                                            disabled={!ability.can('VIEW','CONSULTANT')}
                                                        >
                                                            Back
                                                        </Button>
                                                    </Grid>
                                                </Grid>
                                            </Grid>
                                            <Grid item>
                                            </Grid>
                                        </ThemeProvider>
                                    </Grid>
                            }

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

            
    );
};

export default ConsultantForm;
