import * as Yup from 'yup';
import { LoadingButton } from '@mui/lab';
import { Box, Button, Card, Grid, Stack, Typography } from '@mui/material';
import { Benefit } 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;
  currentCorporateBenefit?: Benefit;
};

export default function CorporateBenefitForm({ isEdit, currentCorporateBenefit }: Props) {
  const { enqueueSnackbar } = useSnackbar();
  const navigate = useNavigate();
  const { corporate_id, benefit_id } = useParams();

  const NewCorporateBenefitSchema = Yup.object().shape({
    budget: Yup.string().required('Budget is required'),
  });

  const defaultValues = useMemo(
    () => ({
      budget: currentCorporateBenefit?.budget || '',
    }),
    [currentCorporateBenefit]
  );

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

  const methods = useForm({
    resolver: yupResolver(NewCorporateBenefitSchema),
    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('/corporates/' + corporate_id + '/corporate-benefits/' + benefit_id, data)
        .then((res) => {
          enqueueSnackbar('Division updated successfully', { variant: 'success' });
        })
        .then((res) => {
          navigate('/corporates/' + corporate_id + '/benefits', { replace: true });
        })
        .catch(({ response }) => {
          enqueueSnackbar('Update Failed : ' + response.data.message, { variant: 'error' });
        });
    }
  };

  return (
    
    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
      <Box sx={{ margin: 1, pb: 2, pl: 4 }}>
        <Grid container>
          <Grid item xs={12} sx={{ padding: 2 }}>
            <Grid container>
              <Stack direction="row" alignItems="center" sx={{ width: '100%' }}>
                <Typography variant="subtitle2" sx={{ mr: 2 }}>
                  ASO/Budget
                </Typography>
                <RHFTextField name="budget" type='number'/>
              </Stack>
            </Grid>
          </Grid>
        </Grid>
        <Stack direction="row" alignItems="center" justifyContent="flex-end">
          <Button
            sx={{marginTop:2}}
            type="submit"
            variant="contained"
            size="large"
            color='inherit'
            onClick={() => navigate(`/corporates/${corporate_id}/benefits`)}
            
          >
            Cancel
          </Button>
          <LoadingButton
            type="submit"
            variant="contained"
            size="large"
            // fullWidth={true}
            loading={isSubmitting}
            sx={{marginTop:2, marginLeft:2}}
          >
            Save
          </LoadingButton>
        </Stack>
      </Box>
    </FormProvider>
  );
}
