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

// ** MUI Imports
import Drawer from '@mui/material/Drawer';
import Select from '@mui/material/Select';
import Grid from '@mui/material/Grid';
import Button from '@mui/material/Button';
import Fade from '@mui/material/Fade';
import MenuItem from '@mui/material/MenuItem';
import { styled } from '@mui/material/styles';
import TextField from '@mui/material/TextField';
import InputLabel from '@mui/material/InputLabel';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import FormControl from '@mui/material/FormControl';
import FormHelperText from '@mui/material/FormHelperText';
import Dialog from '@mui/material/Dialog';
import IconButton from '@mui/material/IconButton';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import InputAdornment from '@mui/material/InputAdornment';
import CardContent from '@mui/material/CardContent';

// ** Third Party Imports
import * as yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm, Controller, useFieldArray } from 'react-hook-form';

// ** Icons Imports
import Close from 'mdi-material-ui/Close';
import Phone from 'mdi-material-ui/Phone';
import EmailOutline from 'mdi-material-ui/EmailOutline';
import AccountOutline from 'mdi-material-ui/AccountOutline';
import MessageOutline from 'mdi-material-ui/MessageOutline';
import CardAccountDetailsOutline from 'mdi-material-ui/CardAccountDetailsOutline';
import BadgeAccountOutline from 'mdi-material-ui/BadgeAccountOutline';
import ImageMultipleOutline from 'mdi-material-ui/ImageMultipleOutline';
import AccountNetworkOutline from 'mdi-material-ui/AccountNetworkOutline';
import City from 'mdi-material-ui/City';
import { AccountPlusOutline, Plus } from 'mdi-material-ui';
import CardAccountPhoneOutline from 'mdi-material-ui/CardAccountPhoneOutline';
import HomeOutline from 'mdi-material-ui/HomeOutline';

// ** Store Imports
import { useDispatch } from 'react-redux';

// ** Actions Imports
import { handleRegister } from 'src/store/apps/contacts';

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

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

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

const defaultValues = {
  identification: '',
  tax_identification: '',
  first_name: '',
  last_name: '',
  username: '',
  password: '',
  organization: '',
  jobTitle: '',
  type_location: '',
  phone: '',
  emails: [],
  phoneType: '',
  phones: [],
  socialNetworks: [],
  addreses: [],
};

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

  // ** State
  const [plan, setPlan] = useState('basic');
  const [role, setRole] = useState('subscriber');

  // ** Hooks
  const dispatch = useDispatch();

  const schema = yup.object().shape({
    identification: yup.string().required(),
    tax_identification: yup.string().min(3, obj => showErrors('Tax Identification', obj.value.length, obj.min)),
    first_name: yup
      .string()
      .min(3, obj => showErrors('First Name', obj.value.length, obj.min))
      .required(),
    last_name: yup
      .string()
      .min(3, obj => showErrors('Last Name', obj.value.length, obj.min))
      .required(),
    username: yup
      .string()
      .min(3, obj => showErrors('Username', obj.value.length, obj.min))
      .required(),
    email: yup.string().email().required(),
    type_location: yup.string().min(3, obj => showErrors('Type Location', obj.value.length, obj.min)),
    phones: yup
      .number()
      .typeError('Phone Number field is required')
      .min(10, obj => showErrors('Phone Number', obj.value.length, obj.min))
      .required(),
    phoneType: yup
      .number()
      .typeError('User thelephone Number field is required')
      .min(10, obj => showErrors('Telephone Number', obj.value.length, obj.min)),
  });

  const {
    reset,
    control,
    setError,
    setValue,
    handleSubmit,
    formState: { errors },
  } = useForm({
    defaultValues,
    // mode: 'onBlur',
    // resolver: yupResolver(schema),
  });

  const onSubmit = data => {
    // dispatch(addUser({ ...data, role, currentPlan: plan }));
    const {
      first_name,
      last_name,
      tax_identification,
      identification,
      username,
      email,
      organization,
      jobTitle,
      type_location,
      phone,
      phoneType,
      socialNetwork,
    } = data;

    handleRegister(
      {
        first_name,
        last_name,
        tax_identification,
        identification,
        username,
        jsonEmail: [{ primary: true, account: email, confirmed: false }],
        type_location,
        organization,
        jobTitle,
        address,
        phone,
        phoneType,
        socialNetwork,
      },
      err => {
        if (err.email) {
          setError('email', {
            type: 'manual',
            message: err.email,
          });
        }
        if (err.username) {
          setError('username', {
            type: 'manual',
            message: err.username,
          });
        }
        if (err.identification) {
          setError('identification', {
            type: 'manual',
            message: err.identification,
          });
        }
        if (err.tax_identification) {
          setError('taxidentification', {
            type: 'manual',
            message: err.tax_identification,
          });
        }
        if (err.first_name) {
          setError('firstname', {
            type: 'manual',
            message: err.first_name,
          });
        }
        if (err.last_name) {
          setError('lastname', {
            type: 'manual',
            message: err.last_name,
          });
        }
      },
    );
  };

  /** INPUTS ARRAYS */

  const networkInput = ({ idx, control, errors }) => (
    <>
      <FormControl sx={{ width: '70%' }}>
        <Controller
          name={`socialNetworks[${idx}].network`}
          control={control}
          rules={{ required: true }}
          render={({ field: { value, onChange, onBlur } }) => (
            <TextField
              value={value}
              onBlur={onBlur}
              label='Social Network'
              onChange={onChange}
              placeholder='@cmlexports'
              InputProps={{
                startAdornment: (
                  <InputAdornment position='start'>
                    <AccountNetworkOutline />
                  </InputAdornment>
                ),
              }}
              error={Boolean(errors.socialNetworks)}
            />
          )}
        />
        {errors.socialNetworks && errors.socialNetworks[idx].network && (
          <FormHelperText sx={{ color: 'error.main' }}>
            {errors.socialNetworks && errors.socialNetworks[idx].network.message}
          </FormHelperText>
        )}
      </FormControl>

      <FormControl sx={{ width: '30%' }}>
        <InputLabel id='red_social'>Type</InputLabel>
        <Controller
          name={`socialNetworks[${idx}].networkType`}
          control={control}
          defaultValue={'Facebook'}
          render={({ field: { value, onChange } }) => (
            <Select
              value={value}
              onChange={onChange}
              fullWidth
              label='Type'
              placeholder='Email'
              labelId='red-social'
              defaultValue='Facebook'
            >
              <MenuItem value='Facebook'>Facebook</MenuItem>
              <MenuItem value='Twitter'>Twitter</MenuItem>
              <MenuItem value='GitHub'>GitHub</MenuItem>
            </Select>
          )}
        />
      </FormControl>
    </>
  );

  const addressInput = ({ idx, control, errors }) => (
    <>
      <FormControl sx={{ width: '80%' }}>
        <Controller
          name={`addresses[${idx}].address`}
          control={control}
          rules={{ required: false }}
          render={({ field: { value, onChange } }) => (
            <TextField
              fullWidth
              label='Address'
              value={value}
              onChange={onChange}
              placeholder='Address'
              InputProps={{
                startAdornment: (
                  <InputAdornment position='start'>
                    <HomeOutline />
                  </InputAdornment>
                ),
              }}
              error={Boolean(errors.address)}
            />
          )}
        />
        {errors.addresses && errors.addresses[idx].address && (
          <FormHelperText sx={{ color: 'error.main' }} id='invoice-address-error'>
            {errors.addresses && errors.addresses[idx].address.message}
          </FormHelperText>
        )}
      </FormControl>
      <FormControl sx={{ width: '20%' }}>
        <InputLabel id='email_type'>Type</InputLabel>
        <Controller
          name={`addresses[${idx}].addressType`}
          control={control}
          defaultValue={'Work'}
          render={({ field: { value, onChange } }) => (
            <Select
              value={value}
              onChange={onChange}
              fullWidth
              label='Type'
              placeholder='Email'
              labelId='email-type'
              defaultValue='Work'
            >
              <MenuItem value='Work'>Work</MenuItem>
              <MenuItem value='Home'>Home</MenuItem>
            </Select>
          )}
        />
      </FormControl>
    </>
  );

  const emailInput = ({ idx, control, errors }) => (
    <>
      <FormControl sx={{ width: '80%' }}>
        <Controller
          control={control}
          name={`emails[${idx}].primary`}
          defaultValue={idx === 0 ? true : false}
          render={({ field: { value, onChange } }) => <Box />}
        />
        <Controller
          control={control}
          name={`emails[${idx}].confirmed`}
          defaultValue={false}
          render={({ field: { value, onChange } }) => <Box />}
        />

        <Controller
          name={`emails[${idx}].email`}
          control={control}
          rules={{ required: true }}
          render={({ field: { value, onChange } }) => (
            <TextField
              fullWidth
              label='Email'
              value={value}
              onChange={onChange}
              placeholder='Email'
              InputProps={{
                startAdornment: (
                  <InputAdornment position='start'>
                    <EmailOutline />
                  </InputAdornment>
                ),
              }}
              error={Boolean(errors.emails)}
            />
          )}
        />
        {errors.emails && errors.emails[idx].email && (
          <FormHelperText sx={{ color: 'error.main' }} id='invoice-email-error'>
            {errors.emails && errors.emails[idx].email.message}
          </FormHelperText>
        )}
      </FormControl>
      <FormControl sx={{ width: '20%' }}>
        <InputLabel id='email_type'>Type</InputLabel>
        <Controller
          name={`emails[${idx}].emailType`}
          control={control}
          defaultValue={'Work'}
          render={({ field: { value, onChange } }) => (
            <Select
              value={value}
              onChange={onChange}
              fullWidth
              label='Type'
              placeholder='Email'
              labelId='email-type'
              defaultValue='Work'
            >
              <MenuItem value='Work'>Work</MenuItem>
              <MenuItem value='Personal'>Personal</MenuItem>
            </Select>
          )}
        />
      </FormControl>
    </>
  );

  const phoneInput = ({ idx, control, errors }) => (
    <>
      <FormControl sx={{ width: '80%' }}>
        <Controller
          name={`phones[${idx}].phone`}
          control={control}
          rules={{ required: true }}
          render={({ field: { value, onChange } }) => (
            <>
              <TextField
                fullWidth
                label='Phone'
                value={value}
                onChange={onChange}
                placeholder='Phone'
                InputProps={{
                  startAdornment: (
                    <InputAdornment position='start'>
                      <CardAccountPhoneOutline />
                    </InputAdornment>
                  ),
                }}
                error={Boolean(errors.phones)}
              />
            </>
          )}
        />
        {errors.phones && errors.phones[idx].phone && (
          <FormHelperText sx={{ color: 'error.main' }} id='invoice-phone-error'>
            {errors.phones && errors.phones[idx].phone.message}
          </FormHelperText>
        )}
      </FormControl>

      <FormControl sx={{ width: '20%' }}>
        <InputLabel id='phone_type'>Type</InputLabel>
        <Controller
          name={`phones[${idx}].type`}
          control={control}
          defaultValue={'Mobile'}
          rules={{ required: true }}
          render={({ field: { value, onChange } }) => (
            <Select
              value={value}
              onChange={onChange}
              fullWidth
              label='Type'
              placeholder='Mobile'
              labelId='phone-type'
              defaultValue='Mobile'
            >
              <MenuItem value='Mobile'>Mobile</MenuItem>
              <MenuItem value='Phone'>Phone</MenuItem>
            </Select>
          )}
        />
        {/* {errors.phones[idx].type && (
        <FormHelperText sx={{ color: 'error.main' }} id='invoice-phoneType-error'>
          {errors.phoneType.message}
        </FormHelperText>
      )} */}
      </FormControl>
    </>
  );

  const [phonesInputs, setPhonesInputs] = useState([new phoneInput({ idx: 0, control, errors })]);
  const [emailsInputs, setEmailsInputs] = useState([new emailInput({ idx: 0, control, errors })]);
  const [addressInputs, setAddressInputs] = useState([new addressInput({ idx: 0, control, errors })]);
  const [networksInputs, setNetworksInputs] = useState([new networkInput({ idx: 0, control, errors })]);

  useEffect(() => {
    if (!show) {
      setEmailsInputs([emailInput]);
      setPhonesInputs([phoneInput]);
      setAddressInputs([addressInput]);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [show]);

  const handleClose = () => {
    setPlan('basic');
    setRole('subscriber');
    setValue('contact', '');
    toggle();
    reset();
  };

  return (
    <Dialog
      fullWidth
      open={open}
      scroll='body'
      onClose={handleClose}
      TransitionComponent={Transition}
      ModalProps={{ keepMounted: true }}
      maxWidth='md'
      onBackdropClick={() => setShow(false)}
    >
      <DialogContent>
        <DialogTitle>
          <Typography variant='h6'>Add Contact</Typography>
        </DialogTitle>
        <Box sx={{ p: 5 }}>
          <form noValidate autoComplete='off' onSubmit={handleSubmit(onSubmit)}>
            <CardContent>
              <Grid container spacing={3}>
                <Grid item xs={12} sm={6}>
                  <FormControl fullWidth sx={{ mb: 6 }}>
                    <Controller
                      name='first_name'
                      control={control}
                      rules={{ required: true }}
                      render={({ field: { value, onChange, onBlur } }) => (
                        <TextField
                          autoFocus
                          value={value}
                          label='First Name'
                          onBlur={onBlur}
                          onChange={onChange}
                          placeholder='John'
                          error={Boolean(errors.first_name)}
                          InputProps={{
                            startAdornment: (
                              <InputAdornment position='start'>
                                <AccountOutline />
                              </InputAdornment>
                            ),
                          }}
                        />
                      )}
                    />
                    {errors.first_name && (
                      <FormHelperText sx={{ color: 'error.main' }}>{errors.first_name.message}</FormHelperText>
                    )}
                  </FormControl>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <FormControl fullWidth sx={{ mb: 6 }}>
                    <Controller
                      name='last_name'
                      control={control}
                      rules={{ required: true }}
                      render={({ field: { value, onChange, onBlur } }) => (
                        <TextField
                          value={value}
                          label='Last Name'
                          onBlur={onBlur}
                          onChange={onChange}
                          placeholder='Doe'
                          InputProps={{
                            startAdornment: (
                              <InputAdornment position='start'>
                                <AccountOutline />
                              </InputAdornment>
                            ),
                          }}
                          error={Boolean(errors.last_name)}
                        />
                      )}
                    />
                    {errors.last_name && (
                      <FormHelperText sx={{ color: 'error.main' }}>{errors.last_name.message}</FormHelperText>
                    )}
                  </FormControl>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <FormControl fullWidth sx={{ mb: 6 }}>
                    <Controller
                      name='identification'
                      control={control}
                      rules={{ required: true }}
                      render={({ field: { value, onChange, onBlur } }) => (
                        <TextField
                          value={value}
                          onBlur={onBlur}
                          label='Identification'
                          onChange={onChange}
                          placeholder='012345678'
                          InputProps={{
                            startAdornment: (
                              <InputAdornment position='start'>
                                <CardAccountDetailsOutline />
                              </InputAdornment>
                            ),
                          }}
                          error={Boolean(errors.identification)}
                        />
                      )}
                    />
                    {errors.identification && (
                      <FormHelperText sx={{ color: 'error.main' }}>{errors.identification.message}</FormHelperText>
                    )}
                  </FormControl>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <FormControl fullWidth sx={{ mb: 6 }}>
                    <Controller
                      name='tax_identification'
                      control={control}
                      rules={{ required: false }}
                      render={({ field: { value, onChange, onBlur } }) => (
                        <TextField
                          value={value}
                          label='Tax Identification'
                          onBlur={onBlur}
                          onChange={onChange}
                          placeholder=''
                          InputProps={{
                            startAdornment: (
                              <InputAdornment position='start'>
                                <CardAccountDetailsOutline />
                              </InputAdornment>
                            ),
                          }}
                          error={Boolean(errors.tax_identification)}
                        />
                      )}
                    />
                    {errors.tax_identification && (
                      <FormHelperText sx={{ color: 'error.main' }}>{errors.tax_identification.message}</FormHelperText>
                    )}
                  </FormControl>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <FormControl fullWidth sx={{ mb: 6 }}>
                    <Controller
                      name='username'
                      control={control}
                      rules={{ required: true }}
                      render={({ field: { value, onChange, onBlur } }) => (
                        <TextField
                          value={value}
                          label='Username'
                          onChange={onChange}
                          onBlur={onBlur}
                          placeholder='johndoe'
                          InputProps={{
                            startAdornment: (
                              <InputAdornment position='start'>
                                <BadgeAccountOutline />
                              </InputAdornment>
                            ),
                          }}
                          error={Boolean(errors.username)}
                        />
                      )}
                    />
                    {errors.username && (
                      <FormHelperText sx={{ color: 'error.main' }}>{errors.username.message}</FormHelperText>
                    )}
                  </FormControl>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <FormControl fullWidth sx={{ mb: 6 }}>
                    <Controller
                      name='type_location'
                      control={control}
                      rules={{ required: false }}
                      render={({ field: { value, onChange, onBlur } }) => (
                        <TextField
                          value={value}
                          onBlur={onBlur}
                          label='Type Location'
                          onChange={onChange}
                          placeholder='Urban'
                          InputProps={{
                            startAdornment: (
                              <InputAdornment position='start'>
                                <City />
                              </InputAdornment>
                            ),
                          }}
                          error={Boolean(errors.type_location)}
                        />
                      )}
                    />
                    {errors.type_location && (
                      <FormHelperText sx={{ color: 'error.main' }}>{errors.type_location.message}</FormHelperText>
                    )}
                  </FormControl>
                </Grid>
                {/* NUMBERS INPUT */}
                <Grid item xs={14}>
                  {
                    <>
                      <Box sx={{ width: 10, height: 10 }} />
                      {new phoneInput({ idx: 0, control, errors })}
                    </>
                  }
                  {phonesInputs.map(input => {
                    return (
                      <>
                        <Box sx={{ width: 10, height: 10 }} />
                        {input}
                      </>
                    );
                  })}

                  <IconButton
                    sx={{ mb: 8 }}
                    onClick={() => {
                      setPhonesInputs([...phonesInputs, new phoneInput({ idx: phonesInputs.length, control, errors })]);
                    }}
                  >
                    <Plus /> <Typography>Add phone</Typography>
                  </IconButton>
                </Grid>

                {/* EMAIL ADDRESSES INPUT */}
                <Grid item xs={14}>
                  {
                    <>
                      <Box sx={{ width: 10, height: 10 }} />
                      {new emailInput({ idx: 0, control, errors })}
                    </>
                  }
                  {emailsInputs.map(input => {
                    return (
                      <>
                        <Box sx={{ width: 10, height: 10 }} />
                        {input}
                      </>
                    );
                  })}

                  <IconButton
                    sx={{ mb: 8 }}
                    onClick={() => {
                      setEmailsInputs([...emailsInputs, new emailInput({ idx: emailsInputs.length, control, errors })]);
                    }}
                  >
                    <Plus /> <Typography>Add email</Typography>
                  </IconButton>
                </Grid>

                {/* ADDRESSES INPUT */}
                <Grid item xs={14}>
                  {
                    <>
                      <Box sx={{ width: 10, height: 10 }} />
                      {new addressInput({ idx: 0, control, errors })}
                    </>
                  }

                  {addressInputs.map(input => {
                    return (
                      <>
                        <Box sx={{ width: 10, height: 10 }} />
                        {input}
                      </>
                    );
                  })}

                  <IconButton
                    sx={{ mb: 8 }}
                    onClick={() => {
                      setAddressInputs([
                        ...addressInputs,
                        new addressInput({ idx: addressInputs.length, control, errors }),
                      ]);
                    }}
                  >
                    <Plus /> <Typography>Add Address</Typography>
                  </IconButton>
                </Grid>

                {/* SOCIAL MEDIA INPUT */}
                <Grid item xs={14}>
                  {networksInputs.map(input => {
                    return (
                      <>
                        <Box sx={{ width: 10, height: 10 }} />
                        {input}
                      </>
                    );
                  })}

                  <IconButton
                    sx={{ mb: 8 }}
                    onClick={() => {
                      setNetworksInputs([
                        ...networksInputs,
                        new networkInput({ idx: networksInputs.length, control, errors }),
                      ]);
                    }}
                  >
                    <Plus /> <Typography>Add Network</Typography>
                  </IconButton>
                </Grid>
              </Grid>
            </CardContent>
          </form>
          <DialogActions>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Button size='large' type='submit' onClick={handleSubmit(onSubmit)} variant='contained' sx={{ mr: 3 }}>
                Submit
              </Button>
              <Button size='large' variant='outlined' color='secondary' onClick={handleClose}>
                Cancel
              </Button>
            </Box>
          </DialogActions>
        </Box>
      </DialogContent>
    </Dialog>
  );
};

export default SidebarAddContact;
