import * as Yup from 'yup';
import { LoadingButton } from "@mui/lab";
import { Button, Card, Grid, Stack, Typography } from "@mui/material";
import { CorporatePlan } from "../../../@types/corporates";
import { FormProvider, RHFSwitch, RHFTextField } from "../../../components/hook-form";
import { useEffect, useMemo } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { useSnackbar } from 'notistack';
import { useNavigate, useParams } from 'react-router-dom';
import axios from '../../../utils/axios';
import { MasterFormularium } from "./Type";


type Props = {
  isEdit: boolean;
  currentMasterForm?: MasterFormularium;
};

export default function CreateUpdateForm({ isEdit, currentMasterForm }: Props) {
  const navigate = useNavigate();
  const { enqueueSnackbar } = useSnackbar();

  const NewCorporatePlanSchema = Yup.object().shape({
    name: Yup.string().required('Name is required'),
  });

  const defaultValues = useMemo(
    () => ({
      name: currentMasterForm?.name || '',
      description: currentMasterForm?.description || '',
    }),
    [currentMasterForm]
  )
  
  useEffect(() => {
    if (isEdit && currentMasterForm) {
      reset(defaultValues);
    }
    if (!isEdit) {
      reset(defaultValues);
    }
  }, [isEdit, currentMasterForm])

  const methods = useForm({
    resolver: yupResolver(NewCorporatePlanSchema),
    defaultValues,
  })

  const {
    reset,
    setError,
    handleSubmit,
    formState: { isSubmitting }
  } = methods;

  const onSubmit = async (data: any) => {
    if (!isEdit) {
      await axios
        .post('/master/formularium-template/store', data)
        .then((res) => {
          enqueueSnackbar('Formularium created succesfully', {variant: 'success'});
        })
        .then((res) => {
          navigate('/master/formularium-template-v2', { replace: true });
        })
        .catch(({ response }) => {
          if (response.status === 422) {
            for (const [key, value] of Object.entries(response.data.errors)) {
              setError(key, { message: value[0] });
              enqueueSnackbar(value[0] ?? 'Failed Processing Reques', { variant: 'error' });
            }
          }
          else {
            enqueueSnackbar('Create Failed : ' + response.data.message, {variant: 'error'});
          }
        });
    } else {
      await axios
        .put(`/master/formularium-template/${currentMasterForm?.id}/update`, data)
        .then((res) => {
          enqueueSnackbar('Formularium updated successfully', { variant: 'success' });
        })
        .then((res) => {
          navigate('/master/formularium-template-v2', { replace: true });
        })
        .catch(({ response }) => {
          enqueueSnackbar(`Update Failed : ${response.data.message}`, { variant: 'error' })
        })
    }
  }

  return (
    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
      <Grid container spacing={2}>
        <Grid item xs={12}>
          <Card sx={{ p:2 }}>
            <Stack spacing={3}>
              <Typography variant='h6' sx={{color: '#19BBBB'}}>Detail</Typography>
              <Typography variant='h6'>Name*</Typography>
              <RHFTextField name='name' label='Name' />
              <Typography variant='h6'>Description*</Typography>
              <RHFTextField name='description' label='Description' />
            </Stack>
          </Card>
          <Stack direction='row' spacing={4} sx={{marginTop: '40px'}}>
            <Grid container item xs={12} justifyContent='flex-end' sx={{p:2}}>
              <Button
                variant='outlined'
                onClick={() => navigate('/master/formularium-template-v2')}
                sx={{
                  p:1,
                  fontWeight: 'bold',
                  outlineColor: 'black',
                  marginRight: '20px',
                  width: 100
                }}
              >
                Cancel
              </Button>
              <LoadingButton
                loading={isSubmitting}
                type='submit'
                variant='contained'
                sx={{
                  p:1,
                  fontWeight: 'bold',
                  backgroundColor: '#19BBBB',
                  "&:hover":{
                    backgroundColor: '#19BBBB', color: '#FFF'
                  },
                  width: 100
                }}
              >
                { isEdit? 'Update' : 'Create' }
              </LoadingButton>
            </Grid>
          </Stack>
        </Grid>
      </Grid>
    </FormProvider>
  )
}