// material-ui
import {
    Grid, TextField, Typography
} from '@mui/material';
import MainCard from "../../components/MainCard";
import * as React from "react";
import {useForm} from "react-hook-form";
import {useEffect, useState} from "react";
import LoadingComponent from "../extra-pages/LoadingComponent";
import {GENERAL_RED_COLOR} from "../../themes/colorConst";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {CHECK_GROUP_DUPLICATE} from "../../utils/ApiPathConst";
import {useParams} from "react-router-dom";
import {isStringEmptyAfterTrim} from "../../utils/CommonFunction";
//import {useParams} from "react-router-dom";

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

const UserGroupInfoCard = ({isCollectData, updateGroupObject,userGroupData,isNewRecord,setUserConfirm,setIsCollectData}) => {
    //const params = useParams();
    const [currentUserGroupData, setCurrentUserGroupData] = React.useState({});
    const [onReady, setOnReady] = useState(false);
    const {register, getValues} = useForm()
    const [errors, setErrors] = useState({});
    const params = useParams();

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

    useEffect(() => {
        //if state data are ready and assign to different field
        if (Object.keys(userGroupData).length > 0 &&currentUserGroupData !== undefined) {
            setOnReady(true);
        }
        else if(isNewRecord){
            setOnReady(true);
        }
    }, [currentUserGroupData]);

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

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

            setErrors(formErrors);

            if (Object.keys(formErrors).length === 0) {
                axios.get(`${apiPath}${CHECK_GROUP_DUPLICATE}`,
                    {
                        params: {
                            "name": values.userGroupName.trim(),
                            "id": params.id,
                        },
                    })
                    .then((response) => {
                        if (response.status === 200) {
                            if(response.data.isTaken){
                                formErrors.userGroupName = `${values.userGroupName} already exists.`;
                                setErrors(formErrors);
                                setUserConfirm(false);
                                setIsCollectData(false);
                            }
                            else if(!response.data.isTaken){
                                const values = getValues();
                                const objectData ={
                                    ...values,
                                }
                                updateGroupObject(objectData);
                            }
                        }
                    })
                    .catch(error => {
                        console.log(error);
                        return true;
                    });
            }
            else if(isCollectData){
                setUserConfirm(false);
                setIsCollectData(false);
            }
        }


    }, [isCollectData]);


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

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

                                <Grid item xs={7} s={7} md={7} lg={6}>
                                    <TextField
                                        fullWidth
                                        inputProps={{maxLength: 50}}
                                        {...register("userGroupName",
                                            {
                                                value: currentUserGroupData.name,
                                            })}
                                        id='groupName'
                                        required
                                        error={!!errors.userGroupName}
                                        helperText={errors.userGroupName}
                                        autoComplete="off"
                                    />
                                </Grid>
                            </Grid>
                        </Grid>

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

                                <Grid item xs={7} s={7} md={7} lg={6}>
                                    <TextField
                                        fullWidth
                                        inputProps={{maxLength: 255}}
                                        {...register("description",
                                            {
                                                value: currentUserGroupData.description,
                                            })
                                        }
                                        id='description'
                                        autoComplete="off"
                                    />
                                </Grid>
                            </Grid>
                        </Grid>
                    </Grid>
                </form>
            </MainCard>
    );
};

export default UserGroupInfoCard;
