// material-ui
import { Grid, Typography, Stack, Box, Button, Tab } from '@mui/material';
import { TabPanel, TabContext, TabList } from '@mui/lab';

import { useEffect, useState } from "react";
import * as React from "react";
//import axios from "axios";
import * as HttpUtils from "utils/HttpUtils";
import { useParams } from "react-router-dom";
import FileList from "components/FileList"
import MainCard from "components/MainCard";
import * as UrlUtils from "utils/ApiPathConst";
import * as DateUtils from 'utils/DateUtils';

import Loadable from 'components/Loadable';
import { lazy } from 'react';
const LoadingComponent = Loadable(lazy(() => import('../../extra-pages/LoadingComponent')));
const UserInformationCard = Loadable(lazy(() => import('./UserInformationCard_Organization')));
const UserInformationPubCard = Loadable(lazy(() => import('./UserInformationCard_Organization_Pub')));
import ForwardIcon from '@mui/icons-material/Forward';
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
import { useNavigate } from 'react-router-dom';
import * as ComboData from "utils/ComboData";
import {getObjectByType, formatUserVerifiedStatus} from "utils/CommonFunction";
const LoginGrid = Loadable(React.lazy(() => import('./LoginGrid')));

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

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


const UserMaintainPage_Organization = () => {
    usePageTitle("userProfile");

    const params = useParams();
    const navigate = useNavigate();
    const [userData, setUserData] = useState({})
    const [orgData, setOrgData] = useState([])
    const [isLoading, setLoding] = useState(true);
    const intl = useIntl();
    const { locale } = intl;
    const [selectedTab, setSelectedTab] = React.useState("1");

    const isPrimaryLocale = locale === 'en' ?"Yes":locale === 'zh-HK' ?"是":"是";
    const notPrimaryLocale = locale === 'en' ?"No":locale === 'zh-HK' ?"否":"否";

    const reqIdRef = React.useRef(0);

    // const _sx = {
    //     ml: 3,
    //     mb: 3,
    //     mt: 3,
    //     mr: 6,
    //     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 handleChange = (event, newValue) => {
        setSelectedTab(newValue);
    }

    useEffect(() => {
        // console.log(userData);
        if (isINDLoggedIn()){
            navigate('/dashboard');
        }else{
            loadData();
        }
    }, []);

    useEffect(() => {
        if (!Array.isArray(orgData) || orgData.length === 0) return;

        setUserData(prev => {
            if (!prev?.orgId) return prev;

            // if already an object, keep it (or re-find to ensure same reference as option)
            const orgIdValue = typeof prev.orgId === "object" ? prev.orgId.id : prev.orgId;

            const found = orgData.find(o => o.id === orgIdValue);
            if (!found) return prev;

            // avoid unnecessary state updates
            if (prev.orgId === found) return prev;

            return { ...prev, orgId: found };
        });
    }, [orgData, userData?.orgId]);

    
    // useEffect(() => {
    //     // console.log(userData);
    //     loadData();
    // }, [locale]);

    // const reloadPage=()=>{
    //     window.location.reload(false);
    // }

    const loadData = () => {        
        const reqId = ++reqIdRef.current;
        setLoding(true);
        if (isGLDLoggedIn()){
            HttpUtils.get({
                url: `${UrlUtils.GET_ORG_USER_PATH}/${params.id}`,
                onSuccess: function (response) {
                    // console.log(response)
                    if (response.data.orgId != null) {
                        // console.log("1a")
                        response.data["addressBus"] = response.orgDetail.data["addressTemp"];
                        response.data["orgContactTel"] = response.orgDetail.data["contactTel"];
                        response.data["orgFaxNo"] = response.orgDetail.data["faxNo"];
                        
                        response.data["contactTel"] = JSON.parse(response.data["contactTel"]);
                        response.data["faxNo"] = JSON.parse(response.data["faxNo"]);

                        response.data["brExpiryDate"] = response.orgDetail.data.brExpiryDate ? DateUtils.dateValue(response.orgDetail.data.brExpiryDate) : "";
                        response.data["brNo"] = response.orgDetail.data.brNo;
                        response.data["enCompanyName"] = response.orgDetail.data.enCompanyName;
                        response.data["chCompanyName"] = response.orgDetail.data.chCompanyName;
                        response.data["chCompanyName"] = response.orgDetail.data.chCompanyName;
                    } else {
                        // console.log("1b")
                        response.data["addressBus"] = JSON.parse(response.data["addressBus"]);
                        response.data["contactTel"] = JSON.parse(response.data["contactTel"]);
                        response.data["faxNo"] = JSON.parse(response.data["faxNo"]);
                        
                        response.data["orgContactTel"] = response.data["contactTel"];
                        response.data["orgFaxNo"] = response.data["faxNo"];
                        
                        response.data["brExpiryDate"] = response.data.brExpiryDate ? DateUtils.dateValue(response.data.brExpiryDate) : "";
                    }
                    // console.log("2")
                    // console.log(response.data)
    
                    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["lastLoginDate"] = response.data.lastLogin ? DateUtils.datetimeStr(response.data.lastLoginDate) : "";
                    response.data["country"] = getObjectByType(ComboData.country, "type", response.data.addressBus?.country);
                    response.data["district"] = getObjectByType(ComboData.district, "type", response.data.addressBus?.district);
                    response.data["addressLine1"] = response.data.addressBus?.addressLine1;
                    response.data["addressLine2"] = response.data.addressBus?.addressLine2;
                    response.data["addressLine3"] = response.data.addressBus?.addressLine3;
    
                    response.data["phoneNumber"] = response.data.contactTel?.phoneNumber;
                    response.data["tel_countryCode"] = response.data.contactTel?.countryCode;
                    response.data["orgPhoneNumber"] = response.data.orgContactTel?.phoneNumber;
                    response.data["org_tel_countryCode"] = response.data.orgContactTel?.countryCode;
    
    
                    response.data["faxNumber"] = response.data.faxNo?.faxNumber;
                    response.data["fax_countryCode"] = response.data.faxNo?.countryCode;
                    response.data["orgFaxNumber"] = response.data.orgFaxNo?.faxNumber;
                    response.data["org_fax_countryCode"] = response.data.orgFaxNo?.countryCode;
                    // response.data["status"] = response.data?.locked?"locked":response.data?.status;
                    response.data["preferLocale"] = getObjectByType(ComboData.Locale, "type", response.data?.preferLocale);
    
                    //response.data["orgId"] = response.data.brExpiryDate?DateUtils.dateValue(response.data.brExpiryDate):"";
    
                    // console.log("3")
                    // console.log(response.data)
                    if (reqId !== reqIdRef.current) return; // ignore stale
                    setOrgData(response.orgList || []);
                    setUserData(response.data);
                    setLoding(false);
                }
            });
        }
        if (isORGLoggedIn()){
            HttpUtils.get({
                url: `${UrlUtils.GET_PUB_ORG_USER_PATH}`,
                onSuccess: function (response) {
                    // console.log(response)
                    response.data["contactTel"] = JSON.parse(response.data["contactTel"]);
                    response.data["faxNo"] = JSON.parse(response.data["faxNo"]);
                    response.data["primaryUser"] = response.data.primaryUser?isPrimaryLocale:notPrimaryLocale;

                    response.data["phoneNumber"] = response.data.contactTel?.phoneNumber;
                    response.data["tel_countryCode"] = response.data.contactTel?.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);
    
                    //response.data["orgId"] = response.data.brExpiryDate?DateUtils.dateValue(response.data.brExpiryDate):"";
                    setUserData(response.data);
                    setOrgData(response.orgList || []);
                    setLoding(false);
                    // console.log(response.data)
                }
            });
        }
    };

    return (
        isLoading ?
            <Grid container sx={{ minHeight: '87vh', mb: 3 }} direction="column" justifyContent="center" alignItems="center">
                <Grid item>
                    <LoadingComponent />
                </Grid>
            </Grid>
            :
            <Grid container sx={{ minHeight: '87vh', backgroundColor: isGLDLoggedIn()?'backgroundColor.default':'#ffffff' }} direction="column">
                <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 Organisation 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} >
                    <Grid container>
                        {isGLDLoggedIn()?
                            <Grid item xs={12} md={12} lg={12}>
                                <Box xs={12} ml={0} mt={-1} mr={0} sx={{ p: 1, borderRadius: '10px' }}>
                                    <UserInformationCard
                                        userData={userData}
                                        loadDataFun={loadData}
                                        orgData={orgData}
                                    />
                                </Box>
                            </Grid>
                        : isORGLoggedIn()?
                            <Grid item xs={12} md={12} lg={12}>
                                <Box xs={12} ml={0} mt={-1} mr={0} sx={{ p: 1, borderRadius: '10px' }}>
                                    <UserInformationPubCard
                                        userData={userData}
                                        loadDataFun={loadData}
                                        orgData={orgData}
                                    />
                                </Box>
                            </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_Organization;
