// material-ui
import {
    Box,
    Grid, Typography
} from '@mui/material';
import ConsultantForm from "./ConsultantForm";
import {useContext, useEffect, useState} from "react";
import * as React from "react";
import axios from "axios";
import {apiPath} from "../../../auth/utils";
import {
    GET_CONSULTANT_PATH,
} from "../../../utils/ApiPathConst";
import LoadingComponent from "../../extra-pages/LoadingComponent";
import {useLocation, useParams} from "react-router-dom";
import ApplicationTable from "./ApplicationTable";
import MainCard from "../../../components/MainCard";
import AbilityContext from "../../../components/AbilityProvider";

import {LIONER_FORM_THEME, CARD_MAX_WIDTH} from "../../../themes/themeConst";
import {ThemeProvider} from "@emotion/react";
import {isObjEmpty} from "../../../utils/Utils";
import { el } from 'date-fns/locale';

const ConsultantPanel = () => {
    const { id } = useParams();
    const location = useLocation();
    const queryParams = new URLSearchParams(location.search);
    
    const [onReady, setOnReady] = useState(false);
    const [isNewRecord, setIsNewRecord] = useState(false);
    const [consultantDetail, setConsultantDetail] = useState({});

    function getConsultantDetail(consultantId) {
        axios.get(`${apiPath}${GET_CONSULTANT_PATH}/${consultantId}`,
        )
            .then((response) => {
                if (response.status === 200) {
                    setConsultantDetail(response.data.data);
                    console.log("response.data:" + response.data.name);
                    // This is the correct place to set the ready state
                    setOnReady(true);
                }
            })
            .catch(error => {
                console.log(error);
                // Handle the error by still setting onReady to true, but maybe with a message
                setOnReady(true); 
                return false;
            });
    }

    useEffect(() => {
        // Check if id is defined and not null
        if(id){
            // Check if it's a new record based on a negative ID
            if (Number(id) < 0) {
                setIsNewRecord(true);
                // Set ready state for new records immediately
                setOnReady(true);
            } else {
                setIsNewRecord(false);
                getConsultantDetail(id);
            }
        } else {
            // This block will handle cases where 'id' is undefined or null
            // If the route is /consultant without an ID, treat it as a new record.
            setIsNewRecord(true);
            setOnReady(true);
        }
    }, [id]);

    useEffect(() => {
        // This code will only run AFTER the 'onReady' state has been updated.
        if(consultantDetail)
            console.log("consultantDetail:" + consultantDetail.name);
        else
            console.log("consultantDetail null");
        
    }, [onReady]); // The dependency array ensures this runs when onReady changes.

    useEffect(() => {
        // This code will only run AFTER the 'onReady' state has been updated.
        if (onReady === true) {
            console.log("The component is now ready!");
        }
    }, [setConsultantDetail]); // The dependency array ensures this runs when onReady changes.
    

    return (
        !onReady ?
            <LoadingComponent/>
            :
            <Grid container rowSpacing={3} columnSpacing={2.75} >
                <ThemeProvider theme={LIONER_FORM_THEME}>
                <Grid item xs={12} s={12} md={12} lg={12}>
                    <Grid container justifyContent="flex-start" alignItems="center">
                        <Grid item xs={3} sx={{mt:-1, mb: -2.25}} >
                            <Box sx={{ display: 'flex', alignItems: 'center'}}>
                                <Typography align="center" variant="h4" >{isNewRecord? "New Consultant" : "Maintain Consultant"}</Typography>
                            </Box>
                        </Grid>
                    </Grid>
                </Grid>

                {/*row 1*/}
                <Grid item xs={12} md={12} lg={12} >
                    <ConsultantForm
                        getConsultantDetail={getConsultantDetail}
                        refConsultantDetail={consultantDetail}
                        isNewRecord={isNewRecord}
                    />
                </Grid>
                </ThemeProvider>
            </Grid>
    );
};

export default ConsultantPanel;