import * as Yup from 'yup';
import { LoadingButton } from "@mui/lab";
import { 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';

type Props = {
  isEdit: boolean;
  currentCorporatePlan?: CorporatePlan;
};

export default function CorporatePlanForm({ isEdit, currentCorporatePlan }: Props) {

  const { enqueueSnackbar } = useSnackbar();
  const navigate = useNavigate();
  const { corporate_id } = useParams();

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

  const defaultValues = useMemo(
    () => ({
      name: currentCorporatePlan?.name || '',
      code: currentCorporatePlan?.code || '',
      active: currentCorporatePlan?.active === 1 ? true : false,
    }),
    [currentCorporatePlan]
  );

  useEffect(() => {
    if (isEdit && currentCorporatePlan) {
      reset(defaultValues);
    }
    if (!isEdit) {
      reset(defaultValues);
    }
  }, [isEdit, currentCorporatePlan]);

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

  const {
    reset,
    watch,
    control,
    setValue,
    getValues,
    setError,
    handleSubmit,
    formState: { isSubmitting },
  } = methods;


  const onSubmit = async (data: any) => {
    if (!isEdit) {
      await axios
      .post('/corporate/' + corporate_id + '/divisions', data)
      .then((res) => {
        enqueueSnackbar('Division created successfully', { variant: 'success' });
      })
      .then((res) => {
        navigate('/corporate/' + corporate_id + '/divisions',  { 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 Request', { variant: 'error' });
          }
        }
        else {
          enqueueSnackbar('Create Failed : '+ response.data.message, { variant: 'error' });
        }
      });
    } else {
      await axios
        .put('/corporate/' + corporate_id + '/divisions/' + currentCorporatePlan?.id , data)
        .then((res) => {
          enqueueSnackbar('Division updated successfully', { variant: 'success' });
        })
        .then((res) => {
          navigate('/corporate/' + corporate_id + '/divisions/' ,  { 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={8}>
            <Card sx={{ p: 2 }}>
                <Stack spacing={3}>

                  <Typography variant="h6">Division Detail</Typography>

                  <RHFTextField name="name" label="Name" />

                  <RHFTextField name="code" label="Code" />

                  <LoadingButton type="submit" variant="contained" size="large" fullWidth={true} loading={isSubmitting}>
                    { isEdit? 'Update' : 'Create' } 
                  </LoadingButton>

                </Stack>
            </Card>
          </Grid>
          <Grid item xs={4}>
            <Card sx={{ p:2 }}>

            <RHFSwitch name="active" label="Active" />
              </Card>
          </Grid>
        </Grid>
      </FormProvider>
  );
}
