// 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 Autocomplete from "@mui/material/Autocomplete";
import axios from "axios";
import {apiPath} from "../../../auth/utils";
import {
    CHECK_EVENT_DUPLICATE, //GET_EVENT_NOTIFICATION_OVERTIME,
    GET_CLIENT_PATH,
    GET_SUB_DIVISION_COMBO_LIST,
    POST_CLIENT_PATH
} from "../../../utils/ApiPathConst";
import {LIONER_BUTTON_THEME, LIONER_LONG_BUTTON_THEME, GENERAL_RED_COLOR} from "../../../themes/colorConst";
import {eventFrequencyCombo, EVENT_REGION_COMBO, EVENT_TYPE_COMBO} from "../../../utils/ComboConst";
import {DatePicker} from "@mui/x-date-pickers/DatePicker";
import dayjs from "dayjs";
import {DemoItem} from "@mui/x-date-pickers/internals/demo";
import {AdapterDayjs} from "@mui/x-date-pickers/AdapterDayjs";
import {LocalizationProvider} from "@mui/x-date-pickers/LocalizationProvider";
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";

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

const ClientForm = ({   refClientDetail,
                       isNewRecord,
                       getClientDetail,
}) => {
    const location = useLocation();
    const queryParams = new URLSearchParams(location.search);
    const refId = queryParams.get("refId");
    const [isFirstInit, setIsFirstInit] = useState(true);

    const params = useParams();
    const navigate = useNavigate();
    const ability = useContext(AbilityContext);
    const [onReady, setOnReady] = useState(false);
    const [errors, setErrors] = useState({});
    const [clientDetail, setClientDetail] = useState({});
    const [isCollectData, setIsCollectData] = useState(false);
    const [userConfirm, setUserConfirm] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const { setIsUploading } = useContext(UploadContext);
    const [refClient, setRefClient] = useState({});

    //form data
    const {register, getValues, setValue} = useForm();
    const [joinDate, setJoinDate] = useState(null);
    // const [awardDate, setAwardDate] = useState(null);
    // const [deadlineDate, setDeadlineDate] = useState(null);
    // const [announceDate, setAnnounceDate] = useState(null);
    // const [selectedRegion, setSelectedRegion] = useState(null);
    // const [selectedType, setSelectedType] = useState(null);
    // const [selectedSubDivision, setSelectedSubDivision] = useState([]);
    // const [fromDate, setFromDate] = useState(null);
    // const [toDate, setToDate] = useState(null);
    // const [reminderFlag, setReminderFlag] = useState(false);
    // const [isFlagFetched, setIsFlagFetched] = useState(false);

    // //reminder option
    // const [selectedFrequency, setSelectedFrequency] = useState(null);
    // const [nextApplicationDate, setNextApplicationDate] = useState(null);

    // //combo list
    // const [subDivisionList, setSubDivisionList] = useState([]);

    const [joinDateError, setJoinDateError] = React.useState(null);
    const [awardDateError, setAwardDateError] = React.useState(null);
    const [deadlineDateError, setDeadlineDateError] = React.useState(null);
    const [announceDateError, setAnnounceDateError] = React.useState(null);
    const [fromError, setFromError] = React.useState(null);
    const [toError, setToError] = React.useState(null);
    // const [nextApplicationDateError, setNextApplicationDateError] = React.useState(null);

    const joinDateErrorMessage = React.useMemo(() => {
        switch (joinDateError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [joinDateError]);

    const awardDateErrorMessage = React.useMemo(() => {
        switch (awardDateError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [awardDateError]);

    const deadlineDateErrorMessage = React.useMemo(() => {
        switch (deadlineDateError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [deadlineDateError]);

    const announceDateErrorMessage = React.useMemo(() => {
        switch (announceDateError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [announceDateError]);

    const fromErrorMessage = React.useMemo(() => {
        switch (fromError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [fromError]);

    const toErrorMessage = React.useMemo(() => {
        switch (toError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [toError]);

    // const nextApplicationDateErrorMessage = React.useMemo(() => {
    //     switch (nextApplicationDateError) {
    //         case 'invalidDate': {
    //             return "Invalid date";
    //         }
    //     }
    // }, [nextApplicationDateError]);
// ==============================|| DELETE WINDOW RELATED ||============================== //
    const [isWindowOpen, setIsWindowOpen] = React.useState(false);

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

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

    const copyClientAsNew = () => {
        navigate(`/event/maintain/-1?refId=${params.id}`);
    }

    // useEffect(()=>{
    //     if(applicationList.length===0){
    //         validateReminder();
    //     }
    // },[joinDate, nextApplicationDate, deadlineDate]);

    // const validateReminder = () =>{
    //     const values = getValues();
    //     let firstIssueDate = null;
    //     let reminderDates = [];
    //     if (joinDate !== null &&
    //         nextApplicationDate !== null &&
    //         values.reminderThreshold !== null &&
    //         values.reminderInterval !== null &&
    //         values.reminderLimit !== null
    //     ) {
    //         //have value
    //         if(applicationList.length <=0){
    //             firstIssueDate = joinDate.add(-values.reminderThreshold,'days');
    //         }
    //         else{
    //             firstIssueDate = nextApplicationDate.add(-values.reminderThreshold, 'days');
    //         }

    //         reminderDates.push(firstIssueDate);
    //         for(let i=1; i < parseInt(values.reminderLimit)+1 ; i++){
    //             reminderDates.push(firstIssueDate.add(i*values.reminderInterval,'days'))
    //         }

    //         for(let j=0; j < reminderDates.length ; j++){
    //             if(reminderDates[j]-deadlineDate > 0){
    //                 setOvertimeWarning(`Estimated reminder exceeds the application deadline, the last reminder will be generated on ${reminderDates[j>1?j-1:0].format('DD/MM/YYYY')}.`);
    //                 return false;
    //             }
    //         }

    //         // setOvertimeWarning("");
    //         return true;
    //     }
    //     return true;
    // }

    function updateData(){
        // if(applicationList.length >0){
        //     notifyDeleteError("Delete restricted. Application exist in this event");
        //     setIsWindowOpen(false);
        // }
        // else{
        axios.delete(`${apiPath}${GET_CLIENT_PATH}/${params.id}`,
        )
            .then((response) => {
                if (response.status === 204) {
                    notifyDeleteSuccess();
                    setIsWindowOpen(false);
                    returnSearchPage();
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
        // }

    }
// ==============================|| DELETE WINDOW RELATED ||============================== //

    // const validateReminderLimit = (value) => {
    //     const maxValue = reminderLimitMax; // Set the maximum value here
    //     if (/^[0-9]\d*$/.test(value) || value === '') {
    //         if (parseInt(value) > maxValue) {
    //             //console.log(value);
    //             setValue("reminderLimit", maxValue)
    //         }
    //     }
    //     else{
    //         setValue("reminderLimit", '');
    //     }
    // };

    // const handleReminderIntervalChange = (event) => {
    //     const inputValue = event.target.value;
    //     if (/^[0-9]\d*$/.test(inputValue) || inputValue === '') {
    //         setValue("reminderInterval", inputValue);
    //     }
    //     else{
    //         setValue("reminderInterval", '');
    //     }
    // };

    // const handleReminderThresholdChange = (event) => {
    //     const inputValue = event.target.value;
    //     if (/^[0-9]\d*$/.test(inputValue) || inputValue === '') {
    //         setValue("reminderThreshold", inputValue);
    //     }
    //     else{
    //         setValue("reminderThreshold", '');
    //     }
    // };

    useEffect(()=>{
        if (!isNewRecord) {
            setRefClient(refClientDetail);
        }
        // //if combo list ready
        // if (subDivisionList.length >0) {
        // }
    },[]);

    // useEffect(()=>{
    //     if(!isObjEmpty(refClient)){
    //         setIsFlagFetched(true);
    //     }
    // },[reminderFlag,refClient]);

    // useEffect(()=>{
    //     if(isFlagFetched){
    //         if(!reminderFlag){
    //             setReminderInterval(null);
    //             setReminderBefore(null);
    //             setReminderLimit(null);
    //             setValue("reminderThreshold",null);
    //             setValue("reminderLimit",null);
    //             setValue("reminderInterval",null);
    //         }
    //     }
    // },[isFlagFetched, refClient, reminderFlag]);

    // useEffect(()=>{
    //     setReminderLimitMax(refReminderLimitMax);
    //     if(!isObjEmpty(refClient) ) {
    //         if(reminderFlag){
    //             setReminderInterval(refReminderInterval);
    //             setReminderBefore(refReminderBefore);
    //             setReminderLimit(refReminderLimit);
    //         }
    //     }
    // },[reminderFlag, refReminderLimit,refReminderInterval,refReminderLimitMax,refReminderBefore,refClient]);

    useEffect(()=>{
        //if ref data ready
        if (!isObjEmpty(refClient)) {
            //checkOvertime();
            if(refId !== null){
                setValue("fullname", refClient.fullname);
                setValue("lastname", refClient.lastname);
                setValue("firstname", refClient.firstname);
                setValue("title", refClient.title);
                setValue("email", refClient.email);
                setValue("phone1", refClient.phone1);
                setValue("phone2", refClient.phone2);
                setValue("remarks", refClient.remarks);
                setValue("caseManagerId", 1);
                setValue("consultantId", 1);
            }
            setJoinDate(dayjs(getDateString(refClient.joinDate)));
        }
    },[refClient]);

    useEffect(()=>{
        if(!isObjEmpty(refClient)) {
            setOnReady(true);
        }
        else if(isNewRecord){
            setOnReady(true);
            setIsEditing(true);
        }
    },[refClient]);
    // },[refClient,selectedSubDivision,selectedRegion,selectedType, joinDate, deadlineDate]);

    // useEffect(()=>{
    //     if(selectedFrequency !== null){
    //         if(selectedFrequency.key === 5 && isNewRecord){
    //         }
    //         else if (isFirstInit && refId !== null){
    //             setIsFirstInit(false);
    //         }
    //         else if(isNewRecord){
    //         }

    //         if (isEditing){
    //             if (joinDate !== null){
    //                 switch(selectedFrequency.key){
    //                     case 1:
    //                         setNextApplicationDate(joinDate.add(1,'month'));
    //                         break;
    //                     case 2:
    //                         setNextApplicationDate(joinDate.add(3,'month'));
    //                         break;
    //                     case 3:
    //                         setNextApplicationDate(joinDate.add(1,'year'));
    //                         break;
    //                     case 4:
    //                         setNextApplicationDate(joinDate.add(6,'month'));
    //                         break;
    //                     default:
    //                         setNextApplicationDate(nextApplicationDate);
    //                         break;
    //                 }
    //             }
    //         }
    //     }
    // },[selectedFrequency,joinDate]);

    // useEffect(() => {
    //     //if state data are ready and assign to different field
    //     axios.get(`${apiPath}${GET_SUB_DIVISION_COMBO_LIST}`)
    //         .then((response) => {
    //             if (response.status === 200) {
    //                 setSubDivisionList(response.data.records);
    //             }
    //         })
    //         .catch(error => {
    //             console.log(error);
    //             return false;
    //         });
    // }, []);

    useEffect(() => {
        //upload latest data to parent
        if(isCollectData){
            const values = getValues();
            const formErrors = {};

            if (isStringEmptyAfterTrim(values.fullname)) {
                formErrors.fullname = 'Client Name is required';
            }


            // if (selectedRegion === null ) {
            //     formErrors.region = 'Client Region is required';
            // }

            // if (isStringEmptyAfterTrim(values.organization)) {
            //     formErrors.organization = 'Client Organization is required';
            // }

            // if (selectedType === null) {
            //     formErrors.type = 'Client Type is required';
            // }

            if (joinDate === null) {
                formErrors.joinDate = 'Join Date is required';
            }

            // if (deadlineDate === null) {
            //     formErrors.deadlineDate = 'Deadline Date is required';
            // }

            // if (awardDate === null) {
            //     formErrors.awardDate = 'Award Date is required';
            // }

            // if (selectedSubDivision.length <= 0){
            //     formErrors.subDivision = 'Sub-Division is required';
            // }

            // if(reminderFlag){
            //     if (selectedFrequency === null){
            //         formErrors.frequency = 'Frequency is required';
            //     }

            //     if (!values.reminderThreshold){
            //         formErrors.threshold = 'Threshold is required';
            //     }

            //     if (!values.reminderInterval){
            //         formErrors.interval = 'Interval is required';
            //     }

            //     if (!values.reminderLimit){
            //         formErrors.limit = 'Limit is required';
            //     }


            //     if(applicationList.length===0){
            //         if(!validateReminder()){
            //             formErrors.calError = "calError";
            //         }
            //     }

            // }

            setErrors(formErrors);
            // if (Object.keys(formErrors).length === 0 //&&
                // !joinDateError && !awardDateError &&
                // !deadlineDateError && !announceDateError &&
                // !fromError && !toError && !nextApplicationDateError
            // ) {
                // axios.get(`${apiPath}${CHECK_EVENT_DUPLICATE}`,
                //     {
                //         params: {
                //             "fullname": values.fullname.trim(),
                //             "id": params.id,
                //         },
                //     })
                //     .then((response) => {
                //         if (response.status === 200) {
                //             const formErrors = {};
                //             if(response.data.isTaken){
                //                 formErrors.fullname = 'Client name must be unique.';
                //                 setErrors(formErrors);
                //                 setIsCollectData(false);
                //                 setUserConfirm(false);
                //             }
                //             else if(!response.data.isTaken){
                //                 if (Object.keys(formErrors).length === 0) {
                //                     let data = {};
                //                     data["id"]  = isNewRecord ? params.id : refClientDetail.id;
                //                     data["fullname"]  = values.fullname;
                //                     data["lastname"]  = values.lastname;
                //                     data["firstname"] = values.firstname;
                //                     data["title"]  = values.title;
                //                     data["email"]  = values.email;
                //                     data["phone1"]  = values.phone1;
                //                     data["phone2"]  = values.phone2;
                //                     data["remarks"]  = values.remarks;
                //                     data["joinDate"]  = joinDate === null ? null : dayjs(joinDate).format('YYYY-MM-DD');
                //                     setClientDetail(data);
                //                 }
                //             }
                //         }
                //     })
                //     .catch(error => {
                //         console.log(error);
                //         return true;
                //     });
            if (Object.keys(formErrors).length === 0) {
                let data = {};
                data["id"]  = isNewRecord ? params.id : refClientDetail.id;
                data["fullname"]  = values.fullname;
                data["lastname"]  = values.lastname;
                data["firstname"] = values.firstname;
                data["title"]  = values.title;
                data["email"]  = values.email;
                data["phone1"]  = values.phone1;
                data["phone2"]  = values.phone2;
                data["remarks"]  = values.remarks;
                data["caseManagerId"]  = 1;
                data["consultantId"]  = 1;
                data["joinDate"]  = joinDate === null ? null : dayjs(joinDate).format('YYYY-MM-DD');
                setClientDetail(data);
            }
            else if(isCollectData){
                setUserConfirm(false);
                setIsCollectData(false);
            }
            // setUserConfirm(false);
            // setIsCollectData(false);
        }
    }, [isCollectData]);

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

    // function createNewApplication(){
    //     navigate('/application/maintain/-1/'+ params.id);
    // }

    useEffect(() => {
        if (userConfirm) {
            postClient();
        }
        setUserConfirm(false);
    }, [clientDetail]);


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

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

    function postClient(){
        setIsUploading(true);
        const temp = trimDataBeforePost(clientDetail);
        // console.log("Posting:");
        // console.log(clientDetail);
        axios.post(`${apiPath}${POST_CLIENT_PATH}`,
            temp,
        )
            .then((response) => {
                if (response.status === 200) {
                    notifySaveSuccess();
                    if(isNewRecord){
                        setIsUploading(false);
                        navigate('/client')
                    }
                    else{
                        setIsUploading(false);
                        getClientDetail(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}}
            >
                <Typography variant="h5" sx={{mt: 3, ml: 3, mb: 1}}>
                    Information
                </Typography>

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

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

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

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

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

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

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

                                <Grid item xs={7} s={7} md={7} lg={7}>
                                    <Autocomplete
                                        disablePortal
                                        id="region-combo"
                                        size="small"
                                        value={selectedRegion === null? null : selectedRegion}
                                        options={EVENT_REGION_COMBO}
                                        onChange={(event, newValue) => {
                                            setSelectedRegion(newValue);
                                        }}
                                        renderInput={(params) => <TextField
                                            {...params}
                                            label=""
                                            error={!!errors.region}
                                            helperText={errors.region}
                                        />}
                                        disabled={!isEditing}
                                        isOptionEqualToValue={isOptionEqualToValue}
                                    />
                                </Grid>
                            </Grid>
                        </Grid> */}

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

                                <Grid item xs={7} s={7} md={7} lg={7}>
                                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                                        <DemoItem  components={['DatePicker']}>
                                            <DatePicker
                                                id="joinDate"
                                                size="small"
                                                required='true'
                                                value={joinDate === null ? null : dayjs(joinDate)}
                                                onChange={(newValue) => setJoinDate(newValue)}
                                                format="DD/MM/YYYY"
                                                onError={(newError) => setJoinDateError(newError)}
                                                slotProps={{
                                                    field: { clearable: true },
                                                    textField: {
                                                        error: !!errors.joinDate || joinDateError,
                                                        helperText: joinDateError ? joinDateErrorMessage : errors.joinDate,
                                                    },
                                                }}
                                                disabled={!isEditing}
                                            />
                                        </DemoItem >
                                    </LocalizationProvider>
                                </Grid>
                            </Grid>
                        </Grid>

                        <Grid item xs={12} sm={12} md={12} lg={5.5} sx={{ml: 3, mr: 3, mb: 3}}>
                            <Grid container alignItems={"center"}>
                                <Grid item xs={4} s={4} md={4} lg={4}
                                      sx={{ml: 3, mr: 3, display: 'flex', alignItems: 'center'}}>
                                    <Typography variant="lionerSize" component="span">
                                    Title:
                                    </Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={6.5}>
                                    <TextField
                                        fullWidth
                                        inputProps={{maxLength: 50}}
                                        size="small"
                                        {...register("title",
                                            {
                                                value: refClient.title,
                                            })}
                                        id='title'
                                        disabled={!isEditing}
                                        autoComplete="off"
                                    />
                                </Grid>
                            </Grid>
                        </Grid>

                        <Grid item xs={12} sm={12} md={12} lg={5.5} sx={{ml: 3, mr: 3, mb: 3}}>
                            <Grid container alignItems={"center"}>
                                <Grid item xs={4} s={4} md={4} lg={4}
                                      sx={{ml: 3, mr: 3, display: 'flex', alignItems: 'center'}}>
                                    <Typography variant="lionerSize" component="span">
                                    Email Address:
                                    </Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={6.5}>
                                    <TextField
                                        fullWidth
                                        inputProps={{maxLength: 50}}
                                        size="small"
                                        {...register("email",
                                            {
                                                value: refClient.email,
                                            })}
                                        id='email'
                                        disabled={!isEditing}
                                        autoComplete="off"
                                    />
                                </Grid>
                            </Grid>
                        </Grid>

                        <Grid item xs={12} sm={12} md={12} lg={5.5} sx={{ml: 3, mr: 3, mb: 3}}>
                            <Grid container alignItems={"center"}>
                                <Grid item xs={4} s={4} md={4} lg={4}
                                      sx={{ml: 3, mr: 3, display: 'flex', alignItems: 'center'}}>
                                    <Typography variant="lionerSize" component="span">
                                    Phone Number:
                                    </Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={6.5}>
                                    <TextField
                                        fullWidth
                                        inputProps={{maxLength: 50}}
                                        size="small"
                                        {...register("phone1",
                                            {
                                                value: refClient.phone1,
                                            })}
                                        id='phone1'
                                        disabled={!isEditing}
                                        autoComplete="off"
                                    />
                                </Grid>
                            </Grid>
                        </Grid>

                        <Grid item xs={12} sm={12} md={12} lg={5.5} sx={{ml: 3, mr: 3, mb: 3}}>
                            <Grid container alignItems={"center"}>
                                <Grid item xs={4} s={4} md={4} lg={4}
                                      sx={{ml: 3, mr: 3, display: 'flex', alignItems: 'center'}}>
                                    <Typography variant="lionerSize" component="span">
                                    Phone Number (Secondary):
                                    </Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={6.5}>
                                    <TextField
                                        fullWidth
                                        inputProps={{maxLength: 50}}
                                        size="small"
                                        {...register("phone2",
                                            {
                                                value: refClient.phone2,
                                            })}
                                        id='phone2'
                                        disabled={!isEditing}
                                        autoComplete="off"
                                    />
                                </Grid>
                            </Grid>
                        </Grid>

                        <Grid item xs={12} s={12} md={12} lg={5.5} sx={{ml: 3, mr: 3, mb: 3}}>
                            <Grid container alignItems={"flex-start"}>
                                <Grid item xs={4} s={4} md={4} lg={4}
                                      sx={{ml: 3, mr: 3, display: 'flex', alignItems: 'center'}}>
                                    <Typography variant="lionerSize" component="span">
                                        Case Manager: <Typography sx={{ color: GENERAL_RED_COLOR }} component="span"></Typography>
                                    </Typography>
                                </Grid>

                                {/* <Grid item xs={7} s={7} md={7} lg={7}>
                                    <Autocomplete
                                        multiple
                                        id="sub-division-demo"
                                        disablePortal
                                        size="small"
                                        options={subDivisionList}
                                        value={selectedSubDivision === null? null : selectedSubDivision}
                                        getOptionLabel={(option) => option.label}
                                        onChange={(event, newValue) => {
                                            setSelectedSubDivision(newValue);
                                        }}
                                        renderInput={(params) => (
                                            <TextField
                                                error={!!errors.subDivision}
                                                helperText={
                                                    errors.subDivision ? (
                                                        <Typography component="div" color="error">
                                                            {errors.subDivision.split("\n").map((line, index) => {
                                                                return (
                                                                    <Typography key={index} >
                                                                        {line}
                                                                    </Typography>
                                                                )
                                                            })}
                                                        </Typography>
                                                    ) : null
                                                }
                                                {...params}
                                                placeholder=""
                                            />
                                        )}
                                        disabled={!isEditing}
                                        isOptionEqualToValue={isOptionEqualToValue}
                                    />
                                </Grid> */}
                            </Grid>
                        </Grid>

                        <Grid item xs={12} s={12} md={12} lg={5.5} sx={{ml: 3, mr: 3, mb: 3}}>
                            <Grid container alignItems={"flex-start"}>
                                <Grid item xs={4} s={4} md={4} lg={4}
                                      sx={{ml: 3, mr: 3, display: 'flex', alignItems: 'center'}}>
                                    <Typography variant="lionerSize" component="span">
                                        Consultant: <Typography sx={{ color: GENERAL_RED_COLOR }} component="span"></Typography>
                                    </Typography>
                                </Grid>

                                {/* <Grid item xs={7} s={7} md={7} lg={7}>
                                    <Autocomplete
                                        multiple
                                        id="sub-division-demo"
                                        disablePortal
                                        size="small"
                                        options={subDivisionList}
                                        value={selectedSubDivision === null? null : selectedSubDivision}
                                        getOptionLabel={(option) => option.label}
                                        onChange={(event, newValue) => {
                                            setSelectedSubDivision(newValue);
                                        }}
                                        renderInput={(params) => (
                                            <TextField
                                                error={!!errors.subDivision}
                                                helperText={
                                                    errors.subDivision ? (
                                                        <Typography component="div" color="error">
                                                            {errors.subDivision.split("\n").map((line, index) => {
                                                                return (
                                                                    <Typography key={index} >
                                                                        {line}
                                                                    </Typography>
                                                                )
                                                            })}
                                                        </Typography>
                                                    ) : null
                                                }
                                                {...params}
                                                placeholder=""
                                            />
                                        )}
                                        disabled={!isEditing}
                                        isOptionEqualToValue={isOptionEqualToValue}
                                    />
                                </Grid> */}
                            </Grid>
                        </Grid>

                        <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={4}
                                      sx={{ml: 3, mr: 3, mt:1, display: 'flex', alignItems: 'flex-start'}}>
                                    <Typography variant="lionerSize" component="span">
                                        Remarks:
                                    </Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={7}>
                                    <TextField
                                        fullWidth
                                        {...register("remarks",
                                            {
                                                value: refClient.remarks,
                                            })}
                                        id='remarks'
                                        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}}>
                                                        <Button
                                                            variant="contained"
                                                            color="delete"
                                                            disabled={isNewRecord || !ability.can('DELETE','EVENT')}
                                                            onClick={handleDeleteClick}
                                                        >
                                                            Delete
                                                        </Button>
                                                        <GeneralConfirmWindow
                                                            isWindowOpen={isWindowOpen}
                                                            title={"Attention"}
                                                            //content={`Confirm to delete Event "${clientDetail.name}" ?`}
                                                            content={`Are you sure to delete this client?`}
                                                            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('EDIT','ALL_RECORD')? false : !ability.can('EDIT','EVENT')}
                                                        >
                                                            Edit
                                                        </Button>
                                                    </Grid>
                                                    <Grid item sx={{ml:1, mr:3, mb:1, mt:2}}>
                                                        <Button
                                                            variant="contained"
                                                            color="cancel"
                                                            onClick={returnSearchPage}
                                                            disabled={ability.can('EDIT','ALL_RECORD')? false : !ability.can('EDIT','EVENT')}
                                                        >
                                                            Back                                                      </Button>
                                                    </Grid>
                                                </Grid>
                                            </Grid>
                                            <Grid item>
                                            </Grid>
                                        </ThemeProvider>
                                    </Grid>
                            }

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

            
    );
};

export default ClientForm;
