// material-ui
import * as React from "react";

import { Grid, Typography, Button, Stack, Box, Tab } from '@mui/material';
import { TabPanel, TabContext, TabList } from '@mui/lab';
import FileList from "components/FileList"
import MainCard from "components/MainCard";
import * as HttpUtils from "utils/HttpUtils";
import { useParams } from "react-router-dom";
import * as UrlUtils from "utils/ApiPathConst";
import * as DateUtils from 'utils/DateUtils';
import ForwardIcon from '@mui/icons-material/Forward';
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'

const BackgroundHead = {
    backgroundImage: `url(${titleBackgroundImg})`,
    width: '100%',
    height: '100%',
    backgroundSize: 'contain',
    backgroundRepeat: 'no-repeat',
    backgroundColor: '#0C489E',
    backgroundPosition: 'right'
}
import Loadable from 'components/Loadable';
import { useNavigate } from "react-router-dom";
import {getObjectByType, formatUserVerifiedStatus} from "utils/CommonFunction";
import * as ComboData from "utils/ComboData";
const LoadingComponent = Loadable(React.lazy(() => import('../../extra-pages/LoadingComponent')));
const UserInformationCard = Loadable(React.lazy(() => import('./UserInformationCard_Individual')));
const UserInformationPubCard = Loadable(React.lazy(() => import('./UserInformationCard_Individual_Pub')));
const LoginGrid = Loadable(React.lazy(() => import('./LoginGrid')));

import {
    isGLDLoggedIn,
    isINDLoggedIn,
    isORGLoggedIn
} from "utils/Utils";
import {FormattedMessage, useIntl} from "react-intl";
import usePageTitle from "components/usePageTitle";
// ==============================|| DASHBOARD - DEFAULT ||============================== //


const UserMaintainPage_Individual = () => {
    usePageTitle("userProfile");
    const intl = useIntl();

    const params = useParams();
    const navigate = useNavigate();
    const [formData, setFormData] = React.useState({})
    const [isLoading, setLoding] = React.useState(true);
    const [selectedTab, setSelectedTab] = React.useState("1");

    React.useEffect(() => {
        if (isORGLoggedIn()){
            navigate('/dashboard');
        }else{
            loadData();
        }
    }, []);

    const handleChange = (event, newValue) => {
        setSelectedTab(newValue);
    }

    const loadData = () => {
        setLoding(true);
        if (isGLDLoggedIn()){
            HttpUtils.get({
                url: `${UrlUtils.GET_IND_USER_PATH}/${params.id}`,
                onSuccess: function (response) {
                    response.data["address"] = JSON.parse(response.data["address"]);
                    response.data["mobileNumber"] = JSON.parse(response.data["mobileNumber"]);
                    response.data["faxNo"] = JSON.parse(response.data["faxNo"]);
    
                    let createDate = DateUtils.datetimeStr(response.data.created);
                    let modifiedBy = DateUtils.datetimeStr(response.data.modified) + ", " + response.data.modifiedBy;
                    response.data["createDate"] = createDate;
                    response.data["modifieDate"] = modifiedBy;
                    response.data["verifiedStatus"] = formatUserVerifiedStatus(
                        response.data,
                        DateUtils.datetimeStr,
                        intl.formatMessage
                    );
    
                    response.data["country"] = getObjectByType(ComboData.country, "type", response.data.address?.country);
                    response.data["district"] = getObjectByType(ComboData.district, "type", response.data.address?.district);
                    response.data["addressLine1"] = response.data.address?.addressLine1;
                    response.data["addressLine2"] = response.data.address?.addressLine2;
                    response.data["addressLine3"] = response.data.address?.addressLine3;
    
                    response.data["phoneNumber"] = response.data.mobileNumber?.phoneNumber;
                    response.data["tel_countryCode"] = response.data.mobileNumber?.countryCode;
    
                    response.data["faxNumber"] = response.data.faxNo?.faxNumber;
                    response.data["fax_countryCode"] = response.data.faxNo?.countryCode;
    
                    response.data["lastLoginDate"] = response.data.lastLogin ? DateUtils.datetimeStr(response.data.lastLogin) : "";
                    response.data["preferLocale"] = getObjectByType(ComboData.Locale, "type", response.data?.preferLocale);
    
                    setFormData(response.data);
                    setLoding(false);
                }
            });
        }
        else if (isINDLoggedIn()){
            HttpUtils.get({
                url: `${UrlUtils.GET_PUB_IND_USER_PATH}`,
                onSuccess: function (response) {
                    response.data["address"] = JSON.parse(response.data["address"]);
                    response.data["mobileNumber"] = JSON.parse(response.data["mobileNumber"]);
                    response.data["faxNo"] = JSON.parse(response.data["faxNo"]);
    
                    response.data["country"] = getObjectByType(ComboData.country, "type", response.data.address?.country);
                    response.data["district"] = getObjectByType(ComboData.district, "type", response.data.address?.district);
                    response.data["addressLine1"] = response.data.address?.addressLine1;
                    response.data["addressLine2"] = response.data.address?.addressLine2;
                    response.data["addressLine3"] = response.data.address?.addressLine3;
    
                    response.data["phoneNumber"] = response.data.mobileNumber?.phoneNumber;
                    response.data["tel_countryCode"] = response.data.mobileNumber?.countryCode;
    
                    response.data["faxNumber"] = response.data.faxNo?.faxNumber;
                    response.data["fax_countryCode"] = response.data.faxNo?.countryCode;
                    
                    response.data["preferLocale"] = getObjectByType(ComboData.Locale, "type", response.data?.preferLocale);
                    // console.log(response.data)
                    setFormData(response.data);
                    setLoding(false);
                }
            });
        }
    };

    return (
        isLoading ?
            <Grid container sx={{ minHeight: '87vh', mb: 3 }} direction="column" justifyContent="center" alignItems="center">
                <Grid item>
                    <LoadingComponent />
                </Grid>
            </Grid>
            :
            <Grid container direction="column" sx={{minHeight: '87vh', backgroundColor: isGLDLoggedIn()?'backgroundColor.default':'#ffffff', maxWidth:'100%' }}>
                <Grid item xs={12}>
                    <div style={BackgroundHead}>
                        <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
                        {isGLDLoggedIn()?
                            <Typography component="h1" ml={15} color='#FFF' variant="h4" sx={{display: { xs: 'none', sm: 'none', md: 'block', pt:2 }}}>
                                Maintain Individual User
                            </Typography>
                        :
                            <Typography component="h1" ml={15} color='#FFF' variant="h4" sx={{display: { xs: 'none', sm: 'none', md: 'block', pt:2 }}}>
                                <FormattedMessage id="userProfile" />
                            </Typography>
                        }
                        </Stack>
                    </div>
                </Grid>
                <Grid item xs={12}>
                    <Button title={intl.formatMessage({ id: "back" })}
                            aria-label={intl.formatMessage({ id: "back" })}
                            sx={{ ml: 3.5, mt: 2 }} style={{ border: '2px solid' }}
                            variant="outlined" onClick={() => { navigate(-1) }}
                    >
                        <ForwardIcon style={{ height: 30, width: 50, transform: "rotate(180deg)" }} />
                    </Button>
                </Grid>
                {/*col 1*/}
                <Grid item xs={12} sm={12} md={12} lg={12} >
                    <Grid container>
                        {isGLDLoggedIn()?
                            <Grid item xs={12} sm={12} md={12} lg={12} >
                                <UserInformationCard
                                    formData={formData}
                                    loadDataFun={loadData}
                                />
                            </Grid>
                        :isINDLoggedIn()?
                            <Grid item xs={12} sm={12} md={12} lg={12} >
                                <UserInformationPubCard
                                    formData={formData}
                                    loadDataFun={loadData}
                                />
                            </Grid>
                            :null
                        }
                        {isGLDLoggedIn()?
                            <Grid item xs={12} md={12} lg={12}>
                                <MainCard elevation={0} border={false} content={false} sx={{maxWidth: '100%', mr:2, width: "-webkit-fill-available"}}>
                                    <TabContext value={selectedTab}>
                                        <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
                                            <TabList  variant="scrollable" onChange={handleChange} aria-label={intl.formatMessage({ id: 'ariaRelatedRecords' })}>
                                                <Tab label="Attachments" value="1" />
                                                <Tab label="Login Log" value="2" />
                                            </TabList>
                                        </Box>
                                        <TabPanel value="1">
                                            <FileList
                                                refId={params.id}
                                                refType={"identification"}
                                            />
                                        </TabPanel>
                                        <TabPanel value="2">
                                            <LoginGrid
                                                u1 = {params.id}
                                            />
                                        </TabPanel>
                                    </TabContext>
                                </MainCard>
                                <br />
                            </Grid>
                            :null
                        }
                    </Grid>
                </Grid>
                {/*col 2*/}
            </Grid>
    );
};


export default UserMaintainPage_Individual;
