import { useNavigate, useParams } from "react-router-dom";
import HeaderBreadcrumbs from "../../../components/HeaderBreadcrumbs";
import Page from "../../../components/Page";
import useSettings from "../../../hooks/useSettings";
import {useContext, useEffect, useMemo, useState } from 'react';
import axios from '../../../utils/axios';
import { useSnackbar } from 'notistack';
import { ConfiguredCorporateContext } from "@/contexts/ConfiguredCorporateContext";
import { Corporate, CorporatePlan } from "@/@types/corporates";
import { MasterFormularium } from "./Type";
import CreateUpdateForm from "./CreateUpdateForm";
import Typography from "@/theme/overrides/Typography";

export default function CreateUpdate() {
  const navigate = useNavigate();
  const { corporate_id, id } = useParams();
  const [corporate, setCorporate] = useState<Corporate|null>();
  const configuredCorporateContext = useContext(ConfiguredCorporateContext)
  
  useEffect(() => {
    setCorporate(configuredCorporateContext.currentCorporate);
  }, [ConfiguredCorporateContext])

  const [ currentCorporatePlan, setCurrentCorporatePlan ] = useState<CorporatePlan>();
  const [ currentMasterForm, setCurrentMasterForm ] = useState<MasterFormularium>();
  const isEdit = !!id;
  
  useEffect(() => {
    if (isEdit) {
      axios.get(`/master/formularium-template/${id}/edit`)
        .then((res) => {
          // setCurrentCorporatePlan(res.data);
          setCurrentMasterForm(res.data);
        })
        .catch((err) => {
          if (err.response.status === 404) {
            navigate('/404');
          }
        })
    }
  }, [corporate_id, id])

  const pageType = !isEdit ? "Create" : "Edit" 
  const pageTitle = `Master Formularium ${pageType}`
  return (
    <Page title={pageTitle}>
      <HeaderBreadcrumbs
        heading={pageTitle}
        links={[
          {
            name: 'Master',
            href: '/master/formularium-template-v2'
          },
          {
            name: 'Formularium',
            href: '/master/formularium-template-v2'
          },
          {
            name: !isEdit ? 'Create' : 'Edit',
            href: !isEdit ? `/master/formularium-template-v2/create` : `/master/formularium-template-v2/${id}/edit`
          }
        ]}
      />

      <CreateUpdateForm isEdit={isEdit} currentMasterForm={currentMasterForm} />
      
    </Page>
  )
}