// material-ui
import { Grid, Typography, Stack, Box, Button } from '@mui/material';
import * as React from "react";
import * as HttpUtils from "utils/HttpUtils";
import * as UrlUtils from "utils/ApiPathConst";
import * as DateUtils from "utils/DateUtils";

import Loadable from 'components/Loadable';
const InfoCard = Loadable(React.lazy(() => import('./OrganizationCard')));
const InfoPubCard = Loadable(React.lazy(() => import('./OrganizationPubCard')));
const Table = Loadable(React.lazy(() => import('./CreditorHistoryTable')));
const LoadingComponent = Loadable(React.lazy(() => import('pages/extra-pages/LoadingComponent')));

import ForwardIcon from '@mui/icons-material/Forward';
import { useNavigate, useParams } from 'react-router-dom';
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
import {getObjectByType} from "utils/CommonFunction";
import * as ComboData from "utils/ComboData";
import {
    isGLDLoggedIn,
    isINDLoggedIn,
    isORGLoggedIn,
    isPrimaryLoggedIn
} from "utils/Utils";
import usePageTitle from "components/usePageTitle";

const BackgroundHead = {
    backgroundImage: `url(${titleBackgroundImg})`,
    width: '100%',
    height: '100%',
    backgroundSize: 'contain',
    backgroundRepeat: 'no-repeat',
    backgroundColor: '#0C489E',
    backgroundPosition: 'right'
}
import {
    FormattedMessage,
    // FormattedMessage,
    useIntl
} from "react-intl";

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


const OrganizationDetailPage = () => {
    // Localized document title/meta for organisation details (GLD)
    usePageTitle("organizationProfile");

    const params = useParams();
    const [formData, setFormData] = React.useState({})
    const [list, setList] = React.useState([])
    const [isLoading, setLoding] = React.useState(true);
    const [isEditMode, setEditMode] = React.useState(false);
    const navigate = useNavigate();
    const intl = useIntl();
    const { locale } = intl;

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

    React.useEffect(() => {
        // console.log(formData);
        if (isINDLoggedIn()||isORGLoggedIn()&&!isPrimaryLoggedIn()){
            navigate('/dashboard');
        }else{
            loadData();
        }
        loadData();
    }, []);

    const loadData = () => {
        setLoding(true);
        if(isGLDLoggedIn()){
            if (params.id > 0) {
                HttpUtils.get({
                    url: UrlUtils.GET_ORG_PATH + "/" + params.id,
                    onSuccess: function (response) {
                        // console.log(response)
                        response.data["country"] = getObjectByType(ComboData.country, "type", response.data.addressTemp?.country);
                        response.data["district"] = getObjectByType(ComboData.district, "type", response.data.addressTemp?.district);
                        response.data["addressLine1"] = response.data.addressTemp?.addressLine1;
                        response.data["addressLine2"] = response.data.addressTemp?.addressLine2;
                        response.data["addressLine3"] = response.data.addressTemp?.addressLine3;
    
                        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["brExpiryDate"] = response.data.brExpiryDate ? DateUtils.dateValue(response.data.brExpiryDate) : "";
                        response.data["orgShortName"] = response.data.orgShortName ? response.data.orgShortName : "N/A" ;
                        setFormData(response.data)
                        setList(response.historyList)
                    }
                });
            }
        }
        if(isPrimaryLoggedIn()){
            HttpUtils.get({
                url: UrlUtils.GET_PUB_ORG_PATH,
                onSuccess: function (response) {
                    // console.log(response)
                    response.data["creditor"] = response.data.creditor!=null?response.data.creditor?isCreditor:notCreditor:notCreditor;
                    response.data["country"] = getObjectByType(ComboData.country, "type", response.data.addressTemp?.country);
                    response.data["district"] = getObjectByType(ComboData.district, "type", response.data.addressTemp?.district);
                    response.data["addressLine1"] = response.data.addressTemp?.addressLine1;
                    response.data["addressLine2"] = response.data.addressTemp?.addressLine2;
                    response.data["addressLine3"] = response.data.addressTemp?.addressLine3;

                    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["brExpiryDate"] = response.data.brExpiryDate ? DateUtils.dateStr(response.data.brExpiryDate) : "" ;
                    setFormData(response.data)
                    setList(response.historyList)
                }
            });
        }
    };


    React.useEffect(() => {
        setLoding(false);
    }, [formData]);

    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' }}>
                <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' }}}>
                                Maintain Organisation
                            </Typography>
                        :
                            <Typography component="h1" ml={15} color='#FFF' variant="h4" sx={{display: { xs: 'none', sm: 'none', md: 'block' }}}>
                                <FormattedMessage id="organizationProfile" />
                            </Typography>
                        }
                        </Stack>
                    </div>
                </Grid>
                <Grid item xs={12}>
                    <Button aria-label={intl.formatMessage({id: 'back'})} title="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>
                        <Grid item xs={12} md={12} lg={12}>
                            <Box xs={12} ml={0} mt={-1} mr={0} sx={{ p: 1, borderRadius: '10px' }}>
                                {isGLDLoggedIn()?
                                    <InfoCard
                                        userData={formData}
                                        loadDataFun={loadData}
                                        id={params.id}
                                        setEditModeFun={setEditMode}
                                    />
                                :
                                    <InfoPubCard
                                        userData={formData}
                                        loadDataFun={loadData}
                                        id={params.id}
                                        setEditModeFun={setEditMode}
                                    />
                                }
                            </Box>
                            <br />
                        </Grid>
                        {isGLDLoggedIn()?
                            <Grid item xs={12} md={12} lg={12}  display={isEditMode?"none":""}>
                                <Box xs={12} ml={0} mt={-1} mr={0} sx={{ pl:4, pr:4, pb:2 }}>
                                    <Grid container sx={{ p: 3, backgroundColor: "#FFF",  borderRadius: '10px' }}>
                                        <Grid item xs={12} sx={{ p:1 }}>
                                            <Table
                                                sx={{ p: 1 }}
                                                recordList={list}
                                            >
                                            </Table>
                                        </Grid>
                                    </Grid>
                                </Box>
                            </Grid>
                        : null
                        }
                    </Grid>
                </Grid>
                {/*col 2*/}
            </Grid>
    );
};


export default OrganizationDetailPage;
