import { makeStyles, Button, TextField, Typography } from '@material-ui/core'
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { asyncAddContact } from '../../../../redux/contacts/operations'

const useStyles = makeStyles({
  container: {
    display: 'flex',
    alignItems: 'center',
    alignContent:'center',
    flexDirection: 'column',
    width: 350,
    margin: '0 auto',
    paddingTop: 64,
    paddingBottom: 24,
  },
  title: {
    marginBottom: 20,
    textAlign: 'center',
  },
  buttonNext: {
    marginTop: 20,
    height: 50,
    color: '#f8f8f8',
    backgroundColor:'#1d74c5',
  },
  textField: {
    marginBottom:20
  }
})

interface IAddContact {
  setSelectedIndex: React.Dispatch<React.SetStateAction<number | null>>
}

const AddContact = ({setSelectedIndex}:IAddContact) => {
  const classes = useStyles()
  const dispatch = useDispatch()
  const [number, setNumber] = useState<string>('')

  const handleTextField = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.split(' ').join('').trim()
    setNumber(value)
  }
  const handleAddContact = async () => {
    dispatch(asyncAddContact(number))
    setNumber('')
    setSelectedIndex(1)  
  }

  const isValidNumber = () => {
    if (number.length < 13 || number.length > 13) return false
    if(number.slice(0,1) === '+') return true
    return true
  }

  const handlePressEnter = (e: React.KeyboardEvent<HTMLDivElement>) => {
    if(e.code === 'Enter' && isValidNumber()) handleAddContact()
  }

 
  return (
    <div onKeyDown={handlePressEnter} className={classes.container} >
      <Typography
        className={classes.title}
        variant="h5"
        color="initial">
        Add new contact
      </Typography>      
      <TextField
        id="number"
        name='NUMBER'
        label="Write down a number,+ is requirement"
        value={number}
        fullWidth
        variant='outlined'
        onChange={handleTextField}
        className={classes.textField}
        required
        />
      {isValidNumber() &&
        <Button
        onClick={handleAddContact}
        className={classes.buttonNext}
        color='primary'
        variant="contained"
        fullWidth
        > ADD
      </Button>}
    </div>
  );
};

export default AddContact;