// src/pages/consultant/ConsultantMaintainPage/index.js ### going to delete!!!

import {
  Box,
  Grid,
  Typography
} from '@mui/material';
import ConsultantForm from "./ConsultantForm";
import { useEffect, useState } 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 { useParams } from "react-router-dom";
import { LIONER_FORM_THEME, CARD_MAX_WIDTH } from "../../../themes/themeConst";
import { ThemeProvider } from "@emotion/react";

const ConsultantPanel = () => {
  const { id } = useParams();
  const [onReady, setOnReady] = useState(false);
  const [isNewRecord, setIsNewRecord] = useState(false);
  const [consultantDetail, setConsultantDetail] = useState({});

  const getConsultantDetail = (consultantId) => {
    axios
      .get(`${apiPath}${GET_CONSULTANT_PATH}/${consultantId}`)
      .then((response) => {
        if (response.status === 200) {
          setConsultantDetail(response.data.data || {});
          setOnReady(true);
        }
      })
      .catch((error) => {
        console.error("Error fetching consultant:", error);
        setOnReady(true); // Show form even on error
      });
  };

  useEffect(() => {
    if (!id) {
      setIsNewRecord(true);
      setOnReady(true);
      return;
    }

    const numericId = Number(id);
    if (isNaN(numericId) || numericId < 0) {
      // Treat as new record
      setIsNewRecord(true);
      setConsultantDetail({});
      setOnReady(true);
    } else {
      setIsNewRecord(false);
      getConsultantDetail(id);
    }
  }, [id]);

  return !onReady ? (
    <LoadingComponent />
  ) : (
    <Grid container rowSpacing={3} columnSpacing={2.75}>
      <ThemeProvider theme={LIONER_FORM_THEME}>
        <Grid item xs={12}>
          <Grid container justifyContent="flex-start" alignItems="center">
            <Grid item xs={12} 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>

        <Grid item xs={12}>
          <ConsultantForm
            getConsultantDetail={getConsultantDetail}
            refConsultantDetail={consultantDetail}
            isNewRecord={isNewRecord}
          />
        </Grid>
      </ThemeProvider>
    </Grid>
  );
};

export default ConsultantPanel;