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_CLIENT_PATH,
    GET_CONSULTANT_COMBO_LIST,
    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";

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({});
    const [consultantComboList, setConsultantComboList] = useState([]);

    // Form data
    const { register, getValues, setValue } = useForm();
    const [dob, setDob] = useState(null);

    const [dobError, setDobError] = 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 dobErrorMessage = React.useMemo(() => {
        switch (dobError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [dobError]);

    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]);

    // 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}`);
    };

    function updateData() {
        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;
            });
    }

    function getConsultantCombo() {
        axios.get(`${apiPath}${GET_CONSULTANT_COMBO_LIST}`, {
            params: {}
        })
            .then((response) => {
                if (response.status === 200) {
                    setConsultantComboList(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    useEffect(() => {
        if (!isNewRecord) {
            setRefClient(refClientDetail);
        }
        getConsultantCombo();
    }, []);

    useEffect(() => {
        if (!isObjEmpty(refClient)) {
            setValue("lastname", refClient.lastname);
            setValue("firstname", refClient.firstname);
            setValue("email", refClient.email);
            setValue("phone1", refClient.phone1);
            setValue("phone2", refClient.phone2);
            setValue("remarks", refClient.remarks);
            setValue("caseManagerId", 1);

            // Set consultantId for Autocomplete
            const selectedConsultant = consultantComboList.find(
                (option) => option.id === refClient.consultantId
            );
            setValue("consultantId", selectedConsultant || null);

            setDob(dayjs(getDateString(refClient.dob)));
        }
    }, [refClient, consultantComboList]);

    useEffect(() => {
        if (!isObjEmpty(refClient)) {
            setOnReady(true);
        } else if (isNewRecord) {
            setOnReady(true);
            setIsEditing(true);
        }
    }, [refClient]);

    useEffect(() => {
        if (isCollectData) {
            const values = getValues();
            const formErrors = {};

            if (isStringEmptyAfterTrim(values.lastname)) {
                formErrors.lastname = 'Last Name is required';
            }

            setErrors(formErrors);
            if (Object.keys(formErrors).length === 0) {
                let data = {};
                data["id"] = isNewRecord ? params.id : refClientDetail.id;
                data["lastname"] = values.lastname;
                data["firstname"] = values.firstname;
                data["email"] = values.email;
                data["phone1"] = values.phone1;
                data["phone2"] = values.phone2;
                data["remarks"] = values.remarks;
                data["caseManagerId"] = 1;
                data["consultantId"] = values.consultantId ? values.consultantId.id : null;
                data["dob"] = dob === null ? null : dayjs(dob).format('YYYY-MM-DD');
                setClientDetail(data);
            } else if (isCollectData) {
                setUserConfirm(false);
                setIsCollectData(false);
            }
        }
    }, [isCollectData]);

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

    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);
        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);
                        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} sm={12} md={12} lg={5.5} sx={{ mt: 1, ml: 3, mr: 3, mb: 3 }}>
                            <Grid container alignItems={"flex-start"}>
                                <Grid item xs={4} sm={4} md={4} lg={4} sx={{ ml: 3, mr: 3, mt: 1, display: 'flex', alignItems: 'flex-start' }}>
                                    <Typography variant="lionerSize" component="span">
                                        Client Code: <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                    </Typography>
                                </Grid>
                                <Grid item xs={7} sm={7} md={7} lg={6.5}>
                                    <TextField
                                        fullWidth
                                        {...register("clientCode", { value: refClient.clientCode })}
                                        id='clientCode'
                                        required
                                        inputProps={{ maxLength: 255, style: { fontSize: '1.1rem' } }}
                                        InputProps={{ style: { minHeight: '42.5px', maxHeight: '50vh' } }}
                                        multiline
                                        maxRows={3}
                                        error={!!errors.lastname}
                                        helperText={errors.lastname}
                                        disabled
                                        autoComplete="off"
                                    />
                                </Grid>
                            </Grid>
                        </Grid>
                        <Grid item xs={12} sm={12} md={12} lg={5.5} sx={{ mt: 1, ml: 3, mr: 3, mb: 3 }}>
                            <Grid container alignItems={"flex-start"}>
                                <Grid item xs={4} sm={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 sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                    </Typography>
                                </Grid>
                                <Grid item xs={7} sm={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}
                                        error={!!errors.lastname}
                                        helperText={errors.lastname}
                                        disabled={!isEditing}
                                        autoComplete="off"
                                    />
                                </Grid>
                            </Grid>
                        </Grid>
                        <Grid item xs={12} sm={12} md={12} lg={5.5} sx={{ mt: 1, ml: 3, mr: 3, mb: 3 }}>
                            <Grid container alignItems={"flex-start"}>
                                <Grid item xs={4} sm={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} sm={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} sm={12} md={12} lg={5.5} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <Grid container alignItems={"center"}>
                                <Grid item xs={4} sm={4} md={4} lg={4} sx={{ ml: 3, mr: 3, display: 'flex', alignItems: 'center' }}>
                                    <Typography variant="lionerSize" component="span">
                                        Date of Birth:
                                    </Typography>
                                </Grid>
                                <Grid item xs={7} sm={7} md={7} lg={7}>
                                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                                        <DemoItem components={['DatePicker']}>
                                            <DatePicker
                                                id="dob"
                                                size="small"
                                                required
                                                value={dob === null ? null : dayjs(dob)}
                                                onChange={(newValue) => setDob(newValue)}
                                                format="DD/MM/YYYY"
                                                onError={(newError) => setDobError(newError)}
                                                slotProps={{
                                                    field: { clearable: true },
                                                    textField: {
                                                        error: !!errors.dob || dobError,
                                                        helperText: dobError ? dobErrorMessage : errors.dob,
                                                    },
                                                }}
                                                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} sm={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} sm={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} sm={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} sm={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={"flex-start"}>
                                <Grid item xs={4} sm={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} sm={7} md={7} lg={6.5}>
                                    <TextField
                                        fullWidth
                                        inputProps={{ maxLength: 50 }}
                                        size="small"
                                        {...register("cm", { value: "N/A" })}
                                        id='cm'
                                        disabled
                                        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={"flex-start"}>
                                <Grid item xs={4} sm={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} sm={7} md={7} lg={6.5}>
                                    <Autocomplete
                                        disablePortal
                                        id="consultant-combo-box"
                                        options={consultantComboList}
                                        getOptionLabel={(option) => option.name || ""}
                                        isOptionEqualToValue={(option, value) => option.id === value.id}
                                        value={getValues("consultantId") || null}
                                        onChange={(event, newValue) => {
                                            setValue('consultantId', newValue || null);
                                        }}
                                        renderInput={(params) => (
                                            <TextField
                                                {...params}
                                                label="Consultant"
                                                name="consultant"
                                            />
                                        )}
                                        disabled={!isEditing}
                                    />
                                </Grid>
                            </Grid>
                        </Grid>
                        <Grid item xs={12} sm={12} md={12} lg={5.5} sx={{ ml: 3, mr: 3, mb: 3, mt: 1 }}>
                            <Grid container alignItems={"flex-start"}>
                                <Grid item xs={4} sm={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} sm={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>
                            {(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', 'CLIENT')}
                                                            onClick={handleDeleteClick}
                                                        >
                                                            Delete
                                                        </Button>
                                                    )}
                                                    <GeneralConfirmWindow
                                                        isWindowOpen={isWindowOpen}
                                                        title={"Attention"}
                                                        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}>
                                                </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', 'CLIENT')}
                                                    >
                                                        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', 'CLIENT')}
                                                    >
                                                        Back
                                                    </Button>
                                                </Grid>
                                            </Grid>
                                        </Grid>
                                        <Grid item>
                                        </Grid>
                                    </ThemeProvider>
                                </Grid>
                            }
                        </Grid>
                    </Grid>
                </form>
            </MainCard>
    );
};

export default ClientForm;