// material-ui
import {
    FormControl, IconButton,
    Grid, InputAdornment, TextField, Typography, Switch
} from '@mui/material';
import MainCard from "../../components/MainCard";
import * as React from "react";
import {useForm} from "react-hook-form";
import Autocomplete from "@mui/material/Autocomplete";
import {useEffect, useState} from "react";
import Checkbox from "@mui/material/Checkbox";
import LoadingComponent from "../extra-pages/LoadingComponent";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {
    CHECK_USER_DUPLICATE, GET_LDAP_USER_COMBO,
    GET_LDAP_USER_LIST,
    GET_SUB_DIVISION_COMBO_LIST
} from "../../utils/ApiPathConst";
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
import {
    convertXmlToObject,
    getComboValueByLabel,
    getObjectById, getObjectByValueName,
    isOptionEqualToValue, isStringEmptyAfterTrim
} from "../../utils/CommonFunction";
import {parseString} from "xml2js";
import {useParams} from "react-router-dom";
import {isObjEmpty} from "../../utils/Utils";
import {GENERAL_RED_COLOR} from "../../themes/colorConst";

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

const UserInformationCard = ({isCollectData, updateUserObject,userData,
                                 isNewRecord,setIsCollectData,setUserConfirm,
                                 requestError}) => {
    const params = useParams();
    const [currentUserData, setCurrentUserData] = React.useState({});
    const [subDivision, setSubDivision] = useState(null);
    const [locked, setLocked] = useState(false);
    const [isLotusNoteUser, setIsLotusNoteUser] = useState(false);
    const [lotusNoteUserList, setLotusNoteUserList] = useState([])
    const [selectedLotusUser, setSelectedLotusUser] = useState(null);
    const [receiveReminder, setReceiveReminder] = useState(false);
    const [subDivisionList, setSubDivisionList] = useState([]);
    const [showPassword, setShowPassword] = React.useState(false);
    const [onReady, setOnReady] = useState(false);
    const {register, getValues, setValue} = useForm()
    const [errors, setErrors] = useState({});
    const [tempLotusDetail, setTempLotusDetail] = useState(null);

    const handleClickShowPassword = () => setShowPassword((show) => !show);
    const handleMouseDownPassword = () => setShowPassword(!showPassword);

    const handleReceiveSwitchToggle = () => {
        setReceiveReminder(!receiveReminder);
    };

    const handleLockSwitchToggle = () => {
        setLocked(!locked);
    };

    const handleLocationCodeChange = (event, value) => {
        if (value.length >2 && !value.includes("(")) {
            fetchLotusUserList(value);
        } else {
            setLotusNoteUserList(lotusNoteUserList);
        }
    };
    // Function to fetch user name options based on locationCode
    const fetchLotusUserListDetail = async (input) => {
        try {
            axios.get(`${apiPath}${GET_LDAP_USER_LIST}`,{
                params:{
                    "EMSDlotus": input,
                }
            })
                .then((response) => {
                    if (response.status === 200) {
                        let xml = response.data;
                        parseString(xml, function (err, result) {
                            const tempRecordList = convertXmlToObject(result.RECORDS.RECORD);
                            const tempRecord = getObjectByValueName(tempRecordList,"EMSDlotus", input)
                            setTempLotusDetail(tempRecord);
                        });
                    }
                })
                .catch(error => {
                    console.log(error);
                    return false;
                });
        } catch (error) {
            console.error('Error fetching user name options:', error);
        }
    };

    const fetchLotusUserList = async (input) => {
        try {
            axios.get(`${apiPath}${GET_LDAP_USER_COMBO}`,{
                params:{
                    "username": input,
                }
            })
                .then((response) => {
                    if (response.status === 200) {
                        setLotusNoteUserList(response.data.records);
                    }
                })
                .catch(error => {
                    console.log(error);
                    return false;
                });
        } catch (error) {
            console.error('Error fetching user name options:', error);
        }
    };

    // const validateEmail = (email) => {
    //     // Regular expression for email validation
    //     const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    //     return emailRegex.test(email);
    // };

    useEffect(() => {
        if(!isObjEmpty(selectedLotusUser)){
            //set basic info
            if(isNewRecord){
                setValue('username', selectedLotusUser.label);
            }
            setValue('email', selectedLotusUser.mail);
            fetchLotusUserListDetail(selectedLotusUser.label);
        }
        else{
            if(isNewRecord){
                setValue('username', null);
                setValue('post', null);
                setValue('fullname',null);
                setValue('email', null);
                setValue("phone1", null);
            }
        }
    }, [selectedLotusUser]);

    useEffect(()=>{
        if(!isObjEmpty(tempLotusDetail)){
            setValue('post',tempLotusDetail.EMSDtitle);
            setValue('fullname',tempLotusDetail.EMSDlastname + " " + tempLotusDetail.EMSDfirstname);
            setValue("phone1", tempLotusDetail.EMSDofftel.substring(0,8));
        }
        else if(isNewRecord){
            setValue('post',"");
            setValue('fullname',"");
            setValue("phone1","");
        }
    },[tempLotusDetail]);
    
    useEffect(() => {
        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(() => {
        setErrors(requestError);
    }, [requestError]);

    useEffect(() => {
        if(isNewRecord){
            setValue("password", null);
            setValue("username", null);
        }
    }, [isLotusNoteUser]);

    useEffect(() => {
        //if user data from parent are not null
        if (Object.keys(userData).length > 0 && userData !== undefined) {
            setIsLotusNoteUser(userData.data.lotusNotesUser);
            setCurrentUserData(userData.data);
        }
    }, [userData]);

    useEffect(() => {
        //if state data are ready and assign to different field
        if (Object.keys(currentUserData).length > 0 &&currentUserData !== undefined) {
            setLocked(currentUserData.locked);
            setReceiveReminder(currentUserData.reminderFlag);
            setSubDivision(getObjectById(subDivisionList, currentUserData.subDivisionId));
            setOnReady(true);
        }
        else if(isNewRecord){
            setLocked(false);
            setOnReady(true);
        }
    }, [currentUserData,subDivisionList]);

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

            if (isStringEmptyAfterTrim(values.username) ) {
                formErrors.username = 'User Name is required';
            }

            if (isStringEmptyAfterTrim(values.password) && !isLotusNoteUser && isNewRecord){
                formErrors.password = "Password is required"
            }

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

            if(isStringEmptyAfterTrim(values.email)){
                formErrors.email = 'Email is required';
            }
            // else if(!validateEmail(values.email)){
            //     formErrors.email = 'Invalid Email';
            // }


            if(subDivision === null){
                formErrors.subDivision = 'Sub-Division is required';
            }

            setErrors(formErrors);

            if (Object.keys(formErrors).length === 0) {
                axios.get(`${apiPath}${CHECK_USER_DUPLICATE}`,
                    {
                        params: {
                            "name": values.username,
                            "id": params.id
                        },
                    })
                    .then((response) => {
                        if (response.status === 200) {
                            const formErrors = {};
                            if(response.data.isTaken){
                                formErrors.username = `${values.username} already exists.`;
                                setErrors(formErrors);
                                setUserConfirm(false);
                                setIsCollectData(false);
                            }
                            else if(!response.data.isTaken){
                                const objectData ={
                                    ...values,
                                    lotusNotesUser: isLotusNoteUser ? true : selectedLotusUser !== null,
                                    selectedLotusUser: (isLotusNoteUser && selectedLotusUser !== null)? selectedLotusUser.account : null,
                                    subDivisionId: subDivision !== null ? subDivision.id : null,
                                    locked: locked,
                                    reminderFlag: receiveReminder,
                                }
                                updateUserObject(objectData);
                            }
                        }
                    })
                    .catch(error => {
                        console.log(error);
                        return true;
                    });
            }
            else if(isCollectData){
                setUserConfirm(false);
                setIsCollectData(false);
            }
        }
    }, [isCollectData]);


    return (
        !onReady ?
            <LoadingComponent/>
            :
            <MainCard elevation={0}
                      content={false}
                      sx={{height:'77.5vh'}}
            >
                <Typography variant="h5" sx={{mt: 1.5, ml: 3, mb: 1}}>
                    Information
                </Typography>

                <form>
                    <Grid item xs={12} s={12} md={12} lg={12} sx={{ml: 3, mr: 3, mb:1}}>
                        <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">
                                    Lotus Note User:
                                </Typography>
                            </Grid>

                            <Grid item xs={1} s={1} md={1} lg={1}>
                                <Checkbox
                                    checked={isLotusNoteUser}
                                    onChange={(event) => setIsLotusNoteUser(event.target.checked)}
                                    name="isLotusNoteUser"
                                    color="primary"
                                    size="medium"
                                    disabled={!isNewRecord}
                                />
                            </Grid>

                            <Grid item xs={6} s={6} md={6} lg={5}>
                                <Autocomplete
                                    disablePortal
                                    id="lotus-note-combo"
                                    value={selectedLotusUser === null ? null : selectedLotusUser}
                                    options={lotusNoteUserList}
                                    disabled={!isLotusNoteUser || !isNewRecord}
                                    size="small"
                                    onInputChange={handleLocationCodeChange}
                                    onChange={(event, newValue) => {
                                        if(lotusNoteUserList.length >0){
                                            if(newValue !== null){
                                                if(getComboValueByLabel(lotusNoteUserList, newValue.label) !== null){
                                                    setSelectedLotusUser(newValue);
                                                }
                                            }
                                            else{
                                                setSelectedLotusUser(null);
                                            }
                                        }
                                    }}
                                    isOptionEqualToValue={isOptionEqualToValue}
                                    renderInput={(params) => <TextField
                                        {...params}
                                        label={"Search LN User"}
                                    />}
                                />
                            </Grid>
                        </Grid>
                    </Grid>

                    <Grid container>
                        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml: 3, mr: 3, mb: 1}}>
                            <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">
                                        Username:
                                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                    </Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={6}>
                                    <FormControl  fullWidth required>
                                        <TextField
                                            required
                                            fullWidth
                                            size="small"
                                            {...register("username",
                                                {
                                                    value: currentUserData.username,
                                                })}
                                            id='username'
                                            InputProps={{
                                                readOnly: isLotusNoteUser,
                                            }}
                                            disabled={!isNewRecord}
                                            error={!!errors.username}
                                            helperText={errors.username}
                                            inputProps={{
                                                maxLength: 50,
                                                form: {
                                                    autocomplete: 'off',
                                                },
                                            }}
                                        />
                                    </FormControl>
                                </Grid>
                            </Grid>
                        </Grid>

                        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml: 3, mr: 3, mb: 1}}>
                            <Grid container alignItems={"center"}>
                                <Grid item xs={4} s={4} md={4} lg={4}
                                      sx={{ml: 3, mr: 3, display: 'flex', alignItems: 'center'}}>
                                    {isLotusNoteUser || !isNewRecord?
                                        <Typography variant="lionerSize" component="span">
                                            Password:
                                        </Typography>
                                        :
                                        <Typography variant="lionerSize" component="span">
                                            Password:
                                            <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                        </Typography>
                                    }
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={6}>
                                    <FormControl  fullWidth required>
                                        <TextField
                                            
                                            fullWidth
                                            size="small"
                                            {...register("password")}
                                            id='password'
                                            type={showPassword ? 'text' : 'password'}
                                            disabled={isLotusNoteUser}
                                            error={!!errors.password}
                                            autoComplete="off"
                                            inputProps={{
                                                maxLength: 50,
                                                autocomplete: 'new-password',
                                                form: {
                                                    autocomplete: 'off',
                                                },
                                            }}
                                            helperText={
                                                errors.password ? (
                                                    <Typography component="div" color="error">
                                                        {errors.password.split("\n").map((line, index) => {
                                                            return (
                                                                <Typography key={index} >
                                                                    {line}
                                                                </Typography>
                                                            )
                                                        })}
                                                    </Typography>
                                                ) : null
                                            }
                                            InputProps={{
                                                endAdornment: (
                                                <InputAdornment position="end">
                                                <IconButton
                                                aria-label="toggle password visibility"
                                                onClick={handleClickShowPassword}
                                                onMouseDown={handleMouseDownPassword}
                                                edge="end"
                                                >
                                            {showPassword ? <Visibility /> : <VisibilityOff />}
                                                </IconButton>
                                                </InputAdornment>
                                                )
                                            }}
                                        />
                                    </FormControl>
                                </Grid>
                            </Grid>
                        </Grid>

                        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml: 3, mr: 3, mb: 1}}>
                            <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">
                                        Full Name:
                                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                    </Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={6}>
                                    <FormControl  fullWidth required>
                                        <TextField
                                            required
                                            fullWidth
                                            size="small"
                                            error={!!errors.fullname}
                                            helperText={errors.fullname}
                                            inputProps={{maxLength: 90}}
                                            {...register("fullname",
                                                {
                                                    value: currentUserData.fullname,
                                                })}
                                            id='fullname'
                                            autoComplete="off"
                                        />
                                    </FormControl>
                                </Grid>
                            </Grid>
                        </Grid>

                        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml: 3, mr: 3, mb: 1}}>
                            <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">
                                        Post:
                                    </Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={6}>
                                    <FormControl  fullWidth required>
                                        <TextField
                                            fullWidth
                                            size="small"
                                            autoComplete="off"
                                            inputProps={{maxLength: 50}}
                                            {...register("post",
                                                {
                                                    value: currentUserData.post,
                                                })}
                                            id='post'
                                        />
                                    </FormControl>
                                </Grid>
                            </Grid>
                        </Grid>

                        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml: 3, mr: 3, mb: 1}}>
                            <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">
                                        Sub-Division:
                                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                    </Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={6}>
                                    <Autocomplete
                                        disablePortal
                                        id="sub-division-combo"
                                        size="small"
                                        value={subDivision === null ? null : subDivision}
                                        options={subDivisionList}
                                        onChange={(event, newValue) => {
                                            setSubDivision(newValue);
                                        }}
                                        renderInput={(params) => (
                                            <TextField
                                                {...params}
                                                //label={content2}
                                                error={!!errors.subDivision}
                                                helperText={errors.subDivision}
                                                InputProps={{
                                                    ...params.InputProps,
                                                    style: {
                                                        height: 'auto',
                                                        overflow: 'hidden',
                                                        paddingTop: '8px', // Adjust as needed for vertical padding
                                                        paddingBottom: '8px', // Adjust as needed for vertical padding
                                                    },
                                                    classes: { input: 'autocomplete-input' },
                                                }}
                                                multiline
                                                maxRows={3}
                                            />
                                        )}
                                        isOptionEqualToValue={isOptionEqualToValue}
                                    />
                                </Grid>
                            </Grid>
                        </Grid>

                        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml: 3, mr: 3, mb: 1}}>
                            <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:
                                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                    </Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={6}>
                                    <FormControl  fullWidth required>
                                        <TextField
                                            fullWidth
                                            size="small"
                                            inputProps={{maxLength: 120}}
                                            {...register("email",
                                                {
                                                    value: currentUserData.email,
                                                })}
                                            id='email'
                                            error={!!errors.email}
                                            helperText={errors.email}
                                            autoComplete="off"
                                        />
                                    </FormControl>
                                </Grid>
                            </Grid>
                        </Grid>

                        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml: 3, mr: 3, mb: 1}}>
                            <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:
                                    </Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={6}>
                                    <FormControl  fullWidth required>
                                        <TextField
                                            fullWidth
                                            size="small"
                                            inputProps={{maxLength: 30}}
                                            {...register("phone1",
                                                {
                                                    value: currentUserData.phone1,
                                                })}
                                            id='phone1'
                                            autoComplete="off"
                                        />
                                    </FormControl>
                                </Grid>
                            </Grid>
                        </Grid>

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

                                <Grid item xs={7} s={7} md={7} lg={6}>
                                    <Switch checked={receiveReminder} onChange={handleReceiveSwitchToggle} />
                                </Grid>

                            </Grid>
                        </Grid>

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

                                <Grid item xs={7} s={7} md={7} lg={6}>
                                    <Switch checked={locked} onChange={handleLockSwitchToggle} />
                                </Grid>

                            </Grid>
                        </Grid>

                    </Grid>
                </form>
            </MainCard>
    );
};

export default UserInformationCard;
