// 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";
import {USER_GROUP_COMBO} from "../../utils/ComboConst";

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

const UserInformationCard = ({isCollectData, updateUserObject,userData,
                                 isNewRecord,setIsCollectData,setUserConfirm,
                                 requestError}) => {
    const params = useParams();
    const [currentUserData, setCurrentUserData] = React.useState({});
    const [userGroup, setUserGroup] = useState(null);
    const [locked, setLocked] = useState(false);
    const [userGroupList, setUserGroupList] = useState([]);
    const [showPassword, setShowPassword] = React.useState(false);
    const [onReady, setOnReady] = useState(false);
    const {register, getValues, setValue} = useForm()
    const [errors, setErrors] = useState({});
    const [twoFactorEnabled, setTwoFactorEnabled] = useState(false);

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

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

    useEffect(() => {
        // axios.get(`${apiPath}${GET_USER_GROUP_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 user data from parent are not null
        if (Object.keys(userData).length > 0 && userData !== undefined) {
            setCurrentUserData(userData.data);
        }
    }, [userData]);

    useEffect(() => {
        if (Object.keys(currentUserData).length > 0 && currentUserData !== undefined) {
            setLocked(currentUserData.locked);
            setTwoFactorEnabled(currentUserData.twoFactorEnabled ?? false);  // ← Add this
            setUserGroup(USER_GROUP_COMBO.find(item => item.id == userData.groupId));
            setOnReady(true);
        }
        else if(isNewRecord){
            setLocked(false);
            setTwoFactorEnabled(false);
            setOnReady(true);
        }
    }, [currentUserData]);

    useEffect(() => {
        //upload latest data to parent
        if(isCollectData){
            let submitUserGroupId = userGroup?.key;
            if (userGroup?.key == userData.groupId) {    // User Group is not updated
                submitUserGroupId = 0;
            }
            
            const values = {
                ...getValues(),
                userGroupId:submitUserGroupId
            };

            const formErrors = {};

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

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

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

            if (userGroup == null) {
                formErrors.userGroup = 'User Group is required';
            }

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

            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,
                                    locked: locked,
                                    twoFactorEnabled: twoFactorEnabled,
                                }
                                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}}>
                    
                </Typography>*/}

                <form>
                    {/* <Grid item xs={12} s={12} md={12} lg={12} sx={{ml: 3, mr: 3, mb:1}}>
                    </Grid> */}

                    <Grid container>
                        <Grid item xs={12} s={12} md={12} lg={12} sx={{mt: 3, 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: {},
                                            // }}
                                            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'}}>
                                    <Typography variant="lionerSize" component="span">
                                        Password:
                                        {isNewRecord && (<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={}
                                            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>

                        <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">
                                        User Group:
                                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                    </Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={6}>
                                    <Autocomplete
                                        disablePortal
                                        // {...register("userGroup",
                                        //     {
                                        //         value: USER_GROUP_COMBO.find(item => item.id = currentUserData.groupId),
                                        //     })}
                                        id="userGroup"
                                        size="small"
                                        value= {userGroup}
                                        // value={userGroup ?? null}
                                        options={USER_GROUP_COMBO}//{userGroupList}
                                        onChange={(event, newValue) => {
                                            setUserGroup(newValue);
                                        }}
                                        renderInput={(params) => (
                                            <TextField
                                                {...params}
                                                //label={content2}
                                                error={!!errors.userGroup}
                                                helperText={errors.userGroup}
                                                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>

                        {!isNewRecord && (
                            <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">
                                            Two-Factor Authentication:
                                        </Typography>
                                    </Grid>

                                    <Grid item xs={7} s={7} md={7} lg={6}>
                                        <Switch
                                            checked={twoFactorEnabled}
                                            onChange={() => setTwoFactorEnabled(!twoFactorEnabled)}
                                            disabled={!twoFactorEnabled}
                                        />
                                    </Grid>
                                </Grid>
                            </Grid>
                        )}

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