// material-ui
import { FiDataGrid } from "components/FiDataGrid";
import {
    Typography, Button, Grid, Stack, useMediaQuery,
    Dialog, DialogTitle, DialogContent, DialogActions,
} from '@mui/material';
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
import Checkbox from '@mui/material/Checkbox';
import * as React from "react";
import * as HttpUtils from "utils/HttpUtils";
import {GET_PUBLIC_ORG_USER_LIST, GET_USER_UNLOCK, GET_SET_PRIMARY_USER, GET_SET_UN_PRIMARY_USER} from "utils/ApiPathConst";
import * as DateUtils from "utils/DateUtils";
import { FormattedMessage, useIntl } from "react-intl";
import { useTheme } from "@emotion/react";
import usePageTitle from "components/usePageTitle";

const BackgroundHead = {
    backgroundImage: `url(${titleBackgroundImg})`,
    width: '100%',
    height: '100%',
    backgroundSize: 'contain',
    backgroundRepeat: 'no-repeat',
    backgroundColor: '#0C489E',
    backgroundPosition: 'right'
}


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


const ManageOrgUserPage = () => {
    // Localized document title/meta for manage org users
    usePageTitle("companyOrUserRecord");

    const intl = useIntl();
    const theme = useTheme();
    const isMdOrLg = useMediaQuery(theme.breakpoints.up('md'));
    const [userId, setUserId] = React.useState("");
    const [isWarningPopUp, setIsWarningPopUp] = React.useState(false);
    const [warningText, setWarningText] = React.useState("");
    const [selectUser, setSelectUser] = React.useState({});

    const _sx = {
        padding: "4 2 4 2",
        boxShadow: 1,
        border: 1,
        borderColor: '#DDD',
        '& .MuiDataGrid-cell': {
            borderTop: 1,
            borderBottom: 1,
            borderColor: "#EEE"
        },
        '& .MuiDataGrid-footerContainer': {
            border: 1,
            borderColor: "#EEE"
        }
    }

    const [_searchCriteria, set_searchCriteria] = React.useState({});
    const [reloadTime, setReloadTime] = React.useState(new Date());

    React.useEffect(() => {
        setUserId(JSON.parse(localStorage.getItem("userData")).id);
    }, []);

    React.useEffect(() => {
        _searchCriteria["reloadTime"] = reloadTime;
        set_searchCriteria(_searchCriteria);
    }, [reloadTime]);


    function onActiveClick(params) {
        HttpUtils.get({
            url: GET_USER_UNLOCK + "/" + params.row.id,
            onSuccess: () => {
                setReloadTime(new Date());
            }
        });
    }

    /** DataGrid `headerName` must be a string; use `renderHeader` for styled markup. */
    const renderStyledHeader = (params) => (
        <Typography variant="h5">{params.colDef.headerName}</Typography>
    );

    function getStatus(params) {
        if (params.row.locked) {
            return (
                <>
                    {getStatusTag({ color: "#525150", text: intl.formatMessage({ id: 'locked' }) })}
                    <Button variant="outlined" onClick={() => onActiveClick(params)}>
                        <FormattedMessage id="unlock" />
                    </Button>
                </>
            )
        } else if (!params.row.verifiedBy) {
            return getStatusTag({ color: "#A36B01", text: intl.formatMessage({ id: 'pendingFor' }) })
        } else if (params.row.status === "active") {
            return getStatusTag({ color: "#578319", text: intl.formatMessage({ id: 'active' }) })
        }
        return getStatusTag({ text: params.row.status })
    }
    
    function getStatusTag({ color = "#000", textColor = "#FFF", text = "" }) {
        return (
            <div style={{ borderRadius: "25px", "background": color, "color": textColor, "padding": "5px 10px 5px 10px" }}><b>{text}</b></div>
        )
    }


    const setPrimaryUser = () => {
        setIsWarningPopUp(false)
        HttpUtils.get(
            {
                url: (!selectUser.row.primaryUser ? GET_SET_PRIMARY_USER : GET_SET_UN_PRIMARY_USER) + "/" + selectUser.row.id,
                onSuccess: function () {
                    setReloadTime(new Date());
                }
            }
        );
    }



    const columns = [
        {
            id: 'username',
            field: 'username',
            headerName: intl.formatMessage({ id: 'loginName' }),
            renderHeader: renderStyledHeader,
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,

        },
        {
            id: 'contactPerson',
            field: 'contactPerson',
            headerName: intl.formatMessage({ id: 'userName' }),
            renderHeader: renderStyledHeader,
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,

        },
        {
            id: 'contactTel',
            field: 'contactTel',
            headerName: intl.formatMessage({ id: 'userContactNumber' }),
            renderHeader: renderStyledHeader,
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,
            valueGetter: (params) => {
                let contactTel = JSON.parse(params.value)
                return contactTel?.countryCode + " " + contactTel?.phoneNumber;
            }
        },
        {
            id: 'emailBus',
            field: 'emailBus',
            headerName: intl.formatMessage({ id: 'userContactEmail' }),
            renderHeader: renderStyledHeader,
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,
        },
        {
            id: 'lastLogin',
            field: 'lastLogin',
            headerName: intl.formatMessage({ id: 'lastLoginDate' }),
            renderHeader: renderStyledHeader,
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,
            valueGetter: (params) => {
                return DateUtils.datetimeStr(params.value);
            }
        },
        {
            id: 'lastApply',
            field: 'lastApply',
            headerName: intl.formatMessage({ id: 'lastSubmissionDate' }),
            renderHeader: renderStyledHeader,
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,
            valueGetter: () => {
                return "--";
            }
        },
        {
            field: 'actions',
            headerName: intl.formatMessage({ id: 'status' }),
            renderHeader: renderStyledHeader,
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,
            cellClassName: 'actions',
            sortable: false,
            filterable: false,
            renderCell: (params) => getStatus(params),
        },
        {
            id: 'primaryUser',
            field: 'primaryUser',
            type: 'bool',
            headerName: intl.formatMessage({ id: 'primary' }),
            renderHeader: renderStyledHeader,
            width: isMdOrLg ? 'auto' : 160,
            flex: isMdOrLg ? 1 : undefined,
            renderCell: (params) => {
                // console.log(params);
                return (
                    <>
                        {params.row.id == userId ?
                            <></> :
                            <Checkbox
                                onClick={() => {
                                    setSelectUser(params);
                                    let str = params.row.primaryUser ?
                                        intl.formatMessage({ id: 'MSG.revokePrimay' },
                                            {
                                                username: params.row.username
                                            })
                                        :
                                        intl.formatMessage({ id: 'MSG.setPrimay' },
                                            {
                                                username: params.row.username
                                            });
                                    setWarningText(str);
                                    setIsWarningPopUp(true);
                                }}
                                checked={params.row.primaryUser}
                            />
                        }
                    </>
                );
            },
        }
    ];

    return (
        <Grid container sx={{ minHeight: '87vh', backgroundColor: 'backgroundColor.default' }} direction="column">
            <Grid item xs={12}>
                <div style={BackgroundHead}>
                    <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
                        <Typography component="h1" ml={15} color='#FFF' variant="h4"  sx={{ "textShadow": "0px 0px 25px #0C489E" }}>
                            <FormattedMessage id="companyOrUserRecord" />
                        </Typography>
                    </Stack>
                </div>
            </Grid>

            <Grid item lg={12} sx={{ padding: 2 }}>
                <FiDataGrid
                    sx={_sx}
                    columns={columns}
                    customPageSize={10}
                    doLoad={{
                        url: GET_PUBLIC_ORG_USER_LIST,
                        params: _searchCriteria,
                    }}
                />
            </Grid>
            <div>
                <Dialog
                    open={isWarningPopUp}
                    onClose={() => setIsWarningPopUp(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogTitle>
                        <FormattedMessage id="confirm" />
                    </DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        <Typography variant="h5" style={{ padding: '16px' }}>{warningText}</Typography>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={() => {
                            setSelectUser({})
                            setIsWarningPopUp(false)
                        }}><FormattedMessage id="cancel" /></Button>
                        <Button onClick={() => setPrimaryUser()}><FormattedMessage id="confirm" /></Button>
                    </DialogActions>
                </Dialog>
            </div>
        </Grid>
    );
};


export default ManageOrgUserPage;
