// material-ui
import * as React from "react";
import * as HttpUtils from "utils/HttpUtils";
import * as UrlUtils from "utils/ApiPathConst";
import * as DateUtils from "utils/DateUtils";
import * as FormatUtils from "utils/FormatUtils";

import {
    Grid,
    Radio,
    FormControlLabel
} from '@mui/material';

import Loadable from 'components/Loadable';
import { lazy } from 'react';
const LoadingComponent = Loadable(lazy(() => import('../../extra-pages/LoadingComponent')));
const PublicNoticeApplyForm = Loadable(lazy(() => import('./PublicNoticeApplyForm')));


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

const ApplyForm = () => {
    const [userData, setUserData] = React.useState(null);
    const [selections, setSelection] = React.useState([]);
    const [isLoading, setLoding] = React.useState(true);

    React.useEffect(() => {
        loadUserData();
    }, []);

    const loadUserData = () => {
        setLoding(true);
        HttpUtils.get({
            url: `${UrlUtils.GET_PUBLIC_NOTICE_getApplyUser}`,
            onSuccess: function (response) {
                response["tel_countryCode"] = response?.contactTelNo?.countryCode;
                response["phoneNumber"] = response?.contactTelNo?.phoneNumber;
                response["fax_countryCode"] = response?.contactFaxNo?.countryCode;
                response["faxNumber"] = response?.contactFaxNo?.faxNumber;
                response["issueId"] = response?.gazetteIssueList[0].id;
                response["remarks"] = "";

                var selection = [];
                for (var i = 0; i < response?.gazetteIssueList?.length; i++) {
                    let data = response.gazetteIssueList[i];
                    let label = getIssueLabel(data);
                    selection.push(<FormControlLabel value={data.id} control={<Radio />} label={label} />);
                }
                setSelection(selection);
                setUserData(response);
            }
        });
    };

    function getIssueLabel(data) {
        return data.year
            + " Vol. " + FormatUtils.zeroPad(data.volume, 3)
            + ", No. " + FormatUtils.zeroPad(data.issueNo, 2)
            + ", " + DateUtils.dateFormat(data.issueDate, "D MMM YYYY (ddd)");
    }

    React.useEffect(() => {
        if (userData !== null) setLoding(false);
    }, [userData]);

    return (
        isLoading ?
            <Grid container sx={{ minHeight: '95vh', mb: 3 }} direction="column" justifyContent="center" alignItems="center">
                <Grid item>
                    <LoadingComponent />
                </Grid>
            </Grid>
            :
            <PublicNoticeApplyForm
                loadedData={userData}
                selections={selections}
            />
    );
};


export default ApplyForm;
