// ** React Imports
import { useEffect,useState, forwardRef } from 'react';

// ** MUI Imports
import Drawer from '@mui/material/Drawer';
import Button from '@mui/material/Button';
import { styled } from '@mui/material/styles';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import Fade from '@mui/material/Fade';
import FormControl from '@mui/material/FormControl';
import FormHelperText from '@mui/material/FormHelperText';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import { useTranslation } from 'react-i18next';

// ** Third Party Imports
import * as yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm, Controller } from 'react-hook-form';
import Swal from 'sweetalert2';
import Translations from 'src/layouts/components/Translations';

// ** Icons Imports
import Close from 'mdi-material-ui/Close';
import { IconButton, InputLabel, OutlinedInput } from '@mui/material';
import {EyePlusOutline} from 'mdi-material-ui';
import {NoteEditOutline} from 'mdi-material-ui';
// ** Actions Imports
import { create, update } from 'src/store/apps/payforms';
import { Translation } from 'react-i18next';
import { Success } from 'src/@core/components/alerts/success-alert';

const showErrors = (field, valueLen, min, max) => {
  if (valueLen === 0) {
    return `${field} field is required`;
  } else if (valueLen > 0 && valueLen < min) {
    return `${field} must be at least ${min} characters`;
  } else if(valueLen >= max) {
    return `${field} must be less than ${max} characters`;
  }else {
    return '';
  }
};

const Transition = forwardRef(function Transition(props, ref) {
  return <Fade ref={ref} {...props} />;
});

const Header = styled(Box)(({ theme }) => ({
  display: 'flex',
  alignItems: 'center',
  padding: theme.spacing(3, 4),
  justifyContent: 'space-between',
  backgroundColor: theme.palette.background.default,
}));

const schema = yup.object().shape({
  payName: yup
    .string()
    .min(4, obj => showErrors('Method of payment', obj.value.length, obj.min))
    .required(),
});

const initialValues = {
  payName: '',
};

const DialogAddPayment = props => {
  const { t } = useTranslation();

  // ** Props
  const { open, toggle, isUpdate, payform, setPayment } = props;
  const [show, setShow] = useState(false);

  const {
    reset,
    control,
    handleSubmit,
    formState: { errors },
  } = useForm({
    defaultValues: initialValues,
    resolver: yupResolver(schema),
  });

  useEffect(() => {
    if (open) {
      if (isUpdate && payform) {
        reset(payform);
      } else {
        reset(initialValues);
      }
    }
  }, [payform, reset, isUpdate, open]);

  const onError = ({ data, status }) => {
    if (status == 404 && data?.message == 'key does not exist') {
      Swal.fire('Error', `¡El campo ${data.key} no fue enviado!`, 'error');
    } else if (status == 404 && data?.message == 'key is required') {
      Swal.fire('Error', `¡El campo ${data.key} es requerido!`, 'error');
    } else if (status == 404 && data?.message == 'payform not found') {
      Swal.fire('Error', '¡LA moneda no esta registrada!', 'error');
    } else {
      Swal.fire('Error', '¡Peticion Fallida!', 'error');
    }
  };

 const onSubmit = data => {
    if (isUpdate) {
      update(
        payform.id,
        data,
        ({ data }) => {
          Swal.fire({
            confirmButtonColor: '#16B1FF',
            title:t('accepted.goodTime'), 
            text:t('accepted.successUpdation'), 
            icon:'success'
          });
          setPayment(payforms => {
            const newpayform = payforms.map(payform => {
              if (payform.id === data.payform.id) {
                return data.payform;
              }

              return payform;
            });

            return newpayform;
          });
          handleClose();
        },
        data => onError(data),
      );
    } else {
      create(
        data,
        ({ data }) => {
          Success(t('accepted.register'))
          setPayment(payforms => [...payforms, data.payform]);
          handleClose();
        },
        data => onError(data),
      );
    }
  };

  const handleClose = () => {
    toggle();
    reset();
  };

  return (
    <Dialog
      fullWidth
      open={open}
      scroll='body'
      onClose={handleClose}
      TransitionComponent={Transition}
      ModalProps={{ keepMounted: true }}
      maxWidth='xs'
      onBackdropClick={() => setShow(false)}
  >
      <Header>
        <Typography variant='h6'>{isUpdate ? <Translations text='edit.terms' /> : <Translations text='add.terms' />}</Typography>
        <Close fontSize='small' onClick={handleClose} sx={{ cursor: 'pointer' }} />
      </Header>
      <Box sx={{ p: 5 }}>
        <form onSubmit={handleSubmit(onSubmit)}>
          <FormControl fullWidth sx={{ mb: 6 }}>
            <InputLabel htmlFor='payName'>
              <Translations text='general.payment' />
            </InputLabel>
            <Controller
              name='payName'
              control={control}
              rules={{ required: true }}
              render={({ field: { value, onChange } }) => (
                <OutlinedInput
                  value={value}
                  label={<Translations text='Method of Payment' />}
                  onChange={onChange}
                  error={Boolean(errors.name)}
                />
              )}
            />
            {errors.name && <FormHelperText sx={{ color: 'error.main' }}>{errors.name.message}</FormHelperText>}
          </FormControl>
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            <Button size='large' type='submit' variant='contained' sx={{ mr: 3 }}>
              <Translations text='general.submit' />
            </Button>
            <Button size='large' variant='outlined' color='secondary' onClick={handleClose}>
              <Translations text='general.cancel' />
            </Button>
          </Box>
        </form>
      </Box>
    </Dialog>
  );    
};

export default DialogAddPayment;