import { makeStyles } from '@material-ui/core'
import { useState } from 'react';
import { useDispatch } from 'react-redux';
import { styled } from '@mui/material/styles';
import Button from '@mui/material/Button';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import ListItemButton from '@mui/material/ListItemButton';
import Avatar from '@mui/material/Avatar';
import ListItemText from '@mui/material/ListItemText';
import ListItemIcon from '@mui/material/ListItemIcon';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import {removeContact } from '../../../../../api-data';
import { actionRightIsOpen } from '../../../../../redux/control/action';
import { TContact } from '../../../../../typescript/redux/contacts/types';
import { TRightIsOpen } from '../../../../../typescript/redux/control/types';
import { firstLetter,slicedWord,timeStampEU,copied,prodAwsS3 } from '../../../../../helpers';

const StyledMenu = styled((props:any) => (
  <Menu
    elevation={0}
    anchorOrigin={{
      vertical: 'top',
      horizontal: 'right',
    }}
    transformOrigin={{
      vertical: 'bottom',
      horizontal: 'right',
    }}
    {...props}
  />
))(({ theme }:any) => ({
  '& .MuiPaper-root': {
    borderRadius: 10,
    marginTop: theme.spacing(0),
    minWidth: 220,
    color:
      theme.palette.mode === 'light' ? 'rgb(55, 65, 81)' : theme.palette.grey[500],
    boxShadow:
      'rgb(255, 255, 255) 0px 0px 0px 0px, rgba(0, 0, 0, 0.05) 0px 0px 0px 1px, rgba(0, 0, 0, 0.1) 0px 10px 15px -3px, rgba(0, 0, 0, 0.05) 0px 4px 6px -2px',
    '& .MuiMenu-list': {
       padding: '8px 8px',
    },
    '& .MuiMenuItem-root': {
      marginBottom: theme.spacing(1),
      '& .MuiSvgIcon-root': {
        fontSize: 21,
        color: theme.palette.text.secondary,
        marginRight: theme.spacing(4),
      }
    },
  },
}));

const useStyles = makeStyles({
  listItem_iconAvatar: {
    marginRight:10
  },
  modalDelete: {
    background: '#ffffff',
    position: 'absolute',
    content:'',
    width: '20%',
    height:'auto',
    left: '40%',
    bottom: '48.5%',
    borderRadius: 10,
    padding: 10,
    display: 'flex',
    flexDirection:'column'
  },  
  overlay: {
    position: 'fixed',
    top: 0,
    left: 0,
    width: '100vw',
    height: '100vh',
    zIndex: 100,
    backgroundColor: 'rgba(104, 105, 104, 0.6)',
    overflowY: 'hidden',
  },
  titleWrapper: {
    display: 'flex',
    justifyContent: 'flex-start',
    alignContent: 'center',
    alignItems:'center'
  },  
})
interface IContactItem {
  contact: TContact,
  handleListItemClick: (companionId: string) => void,
  rightIsOpen: TRightIsOpen,
}
const  ContactItem = ({contact,handleListItemClick,rightIsOpen}:IContactItem) => {
  const classes = useStyles()
  const dispatch = useDispatch()
  const [anchorEl, setAnchorEl] = useState<any>(null);
  const [selected, setSelected] = useState<boolean>(false);
  const [modal,setModal] = useState<boolean>(false)
  const open = Boolean(anchorEl);
  const { name, lastName, avatarUrl, color, companionId,createdAt, number,_id } = contact

  const handleClose = (type: string | undefined): void => {
    if (type === 'copy') copied('Number')
    if (type === 'delete') setModal(true)
    setAnchorEl(null)
    setSelected(false)
  }

  const handleDeleteModal = (e: any) => {
    const id = e.target.id
    if (id === 'overlay' || id === 'cancel') return setModal(false)
    if (id === 'delete') {
      rightIsOpen === 'edit'&&dispatch(actionRightIsOpen('credentials'))
      removeContact(_id)
      setModal(false)
    }
  }  
  const handleContextMenu = (e: React.MouseEvent<HTMLDivElement>):void => {
    e.preventDefault()
    setAnchorEl(e.currentTarget)
    setSelected(true)
  } 

  return (
    <div>
      <ListItemButton
        selected={selected}
        onClick={() => handleListItemClick(companionId)}
        onContextMenu={(e) => handleContextMenu(e)}
      >
        <ListItemIcon className={classes.listItem_iconAvatar}>
        <Avatar alt={name} src={avatarUrl?`${prodAwsS3}/${avatarUrl}`:undefined}
          sx={{ background: color, width: 54, height: 54 }}>
          {!avatarUrl&&`${firstLetter(name)}${firstLetter(lastName)}`}
          </Avatar>
        </ListItemIcon> 
        <ListItemText primary={`${firstLetter(name)}${slicedWord(name, 15, 1)}
          ${firstLetter(lastName)}${slicedWord(lastName, 15, 1)}`}
          secondary={`Registered since ${timeStampEU(createdAt)}`} />
      </ListItemButton>      
      <StyledMenu
        id="demo-positioned-menu"
        aria-labelledby="demo-positioned-button"
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
      >
        <CopyToClipboard onCopy={() => handleClose('copy')} text={number}>
          <MenuItem>
            <ContentCopyIcon />
             Copy number
          </MenuItem>
        </CopyToClipboard>
        <MenuItem style={{color:'#f02a2a'}} onClick={() => handleClose('delete')}>
            <DeleteOutlineIcon style={{color:'#f02a2a'}}/>
            Delete contact
        </MenuItem>        
      </StyledMenu>
     {modal&&<div onClick={handleDeleteModal} className={classes.overlay} id='overlay'>
      <div className={classes.modalDelete}>
        <div className={classes.titleWrapper}>
          <Avatar alt={name} src={avatarUrl?`${prodAwsS3}/${avatarUrl}`:undefined}
            sx={{ background: color, width: 38, height: 38,marginRight:2}}>
            {`${firstLetter(name)}${firstLetter(lastName)}`}
          </Avatar>
          <h3 style={{color: '#2c2c2c'}}>Delete contact</h3>
         </div>
          <p style={{ color: '#050505' }}>{`Are you sure you want to delete contact
            ${`${firstLetter(name)}${slicedWord(name, 15, 1)}
            ${firstLetter(lastName)}${slicedWord(lastName, 15, 1)}`}?`}</p>
          <Button id='delete' variant="text" color="error" style={{fontWeight:500,fontSize:22}}>
            DELETE CONTACT
          </Button>         
          <Button id='cancel' variant="text" style={{fontWeight:500,fontSize:22}}>
             CANCEL
          </Button>
        </div>  
    </div>}
    </div>
  );
}
export default ContactItem