import { useState, useRef, useEffect } from 'react';
import { Box, Typography, IconButton, OutlinedInput } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { PrimaryButton } from '../common/Buttons/Buttons';

const InlineTagInput = ({ onSaveTags }) => {
  const [tags, setTags] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [isFocused, setIsFocused] = useState(false);
  const inputRef = useRef(null);
  const wrapperRef = useRef(null);

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.style.width = `${Math.max(150, inputValue.length * 8)}px`;
    }
  }, [inputValue]);

  const handleWrapperClick = () => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Enter' || e.key === ',') {
      e.preventDefault();
      addTag();
    } else if (e.key === 'Backspace' && inputValue === '' && tags.length > 0) {
      removeTag(tags.length - 1);
    }
  };

  const addTag = () => {
    const trimmedValue = inputValue.trim().replace(/,+$/, '');

    if (trimmedValue && !tags.includes(trimmedValue)) {
      setTags([...tags, trimmedValue]);
      setInputValue('');
    } else if (trimmedValue) {
      setInputValue('');
    }
  };

  const handlePaste = (e) => {
    e.preventDefault();
    const pastedText = e.clipboardData.getData('text');
    const newTags = pastedText
      .split(/[,;\n\t]/)
      .map((tag) => tag.trim())
      .filter((tag) => tag.length > 0 && !tags.includes(tag));

    if (newTags.length > 0) {
      setTags([...tags, ...newTags]);
    }
  };

  const removeTag = (indexToRemove) => {
    setTags(tags.filter((_, index) => index !== indexToRemove));
  };

  const handleClearAll = () => {
    setTags([]);
    setInputValue('');
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  const handleBlur = () => {
    setIsFocused(false);
    if (inputValue.trim()) {
      addTag();
    }
  };

  const handleSaveTags = () => {
    if (onSaveTags) {
      onSaveTags(tags);
      handleClearAll();
    }
  };
  const shouldShowClearButton = tags.length > 0 || inputValue.length > 0;

  return (
    <Box
      sx={{
        border: '1px dashed #e0dfe0',
        borderRadius: '0.75rem',
        padding: '1rem',
        minHeight: '6rem',
        maxHeight: 'max-content',
        background: '#fafafa',
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      <Box sx={{ display: 'flex', gap: '.75rem', alignItems: 'flex-start' }}>
        <Box
          ref={wrapperRef}
          sx={{
            border: '1px solid #e0dfe0',
            borderRadius: '0.5rem',
            padding: '0.38rem 0.75rem',
            width: '100%',
            position: 'relative',
            borderColor: isFocused ? '#a6ce39' : '#e0dfe0',
            boxShadow: isFocused ? '0 0 0 2px rgba(166, 206, 57, 0.15)' : '',
            minHeight: '3.25rem',
            height: 'max-content',
            cursor: 'text',
            backgroundColor: 'white',
            transition: 'all 0.2s ease',
            '&:hover': {
              borderColor: isFocused ? '#a6ce39' : '#e0dfe0',
            },
          }}
          onClick={handleWrapperClick}
        >
          <Box
            sx={{
              display: 'flex',
              flexWrap: 'wrap',
              gap: '0.25rem',
              rowGap: '0.25rem',
              padding: 0,
              minHeight: '3.25rem',
            }}
          >
            {tags.map((tag, index) => (
              <Box
                key={index}
                sx={{
                  display: 'flex',
                  gap: '0.375rem',
                  border: '1px solid #e0dfe0',
                  borderRadius: '624.94rem',
                  padding: '0.12rem 0.75rem',
                  height: '1.25rem',
                  '&:hover': {
                    transition: 'all 0.2s ease',
                    transform: 'scale(1.05)',
                  },
                }}
              >
                <Typography
                  sx={{
                    fontWeight: 400,
                    fontSize: '0.75rem',
                    lineHeight: '133%',
                    color: '#323031',
                    padding: 0,
                    opacity: 0.8,
                  }}
                >
                  {tag}
                </Typography>
                <Box
                  component="button"
                  sx={{
                    background: 'none',
                    border: 'none',
                    padding: 0,
                    width: '0.875rem',
                    height: 'max-content',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    cursor: 'pointer',
                    '& svg': {
                      width: '0.875rem',
                      height: '0.875rem',
                    },
                  }}
                  onClick={(e) => {
                    e.stopPropagation();
                    removeTag(index);
                  }}
                  aria-label={`Удалить ${tag}`}
                >
                  <CloseIcon />
                </Box>
              </Box>
            ))}

            <OutlinedInput
              inputRef={inputRef}
              value={inputValue}
              onChange={handleInputChange}
              onKeyDown={handleKeyDown}
              onPaste={handlePaste}
              onFocus={() => setIsFocused(true)}
              onBlur={handleBlur}
              placeholder={tags.length === 0 ? 'Укажите пользователя(ей)' : ''}
              autoComplete="off"
              sx={{
                height: '1.25rem',
                '& fieldset': {
                  border: 'none !important',
                },
                '& .MuiOutlinedInput-input': {
                  padding: 0,
                  flex: 1,
                  fontSize: '0.88rem',
                  width: '15rem !important',
                  '&:focus': {
                    outline: 'none',
                  },
                },
              }}
            />
          </Box>
          <IconButton
            sx={{
              position: 'absolute',
              top: '0.5rem',
              right: '0.5rem',
              width: '1.5rem',
              height: '1.5rem',
              padding: '0.25rem',
              backgroundColor: '#fff',
              opacity: shouldShowClearButton ? 1 : 0,
              visibility: shouldShowClearButton ? 'visible' : 'hidden',
              transition: 'all 0.2s ease',
              zIndex: 1,
              opacity: shouldShowClearButton ? 0.7 : 0,
              '&:hover': {
                opacity: 1,
              },
              '& svg': {
                width: '0.875rem',
                height: '0.875rem',
                color: '#666',
              },
            }}
            onClick={(e) => {
              e.stopPropagation();
              handleClearAll();
            }}
          >
            <CloseIcon />
          </IconButton>
        </Box>
        {onSaveTags && (
          <PrimaryButton
            onClick={handleSaveTags}
            show={shouldShowClearButton.toString()}
          >
            Добавить
          </PrimaryButton>
        )}
      </Box>

      <Typography
        variant="caption"
        sx={{
          margin: 0,
          padding: 0,
          fontSize: '0.75rem',
          color: '#323031',
          opacity: 0.8,
        }}
      >
        Введите логины через запятую и нажмите + или Enter
      </Typography>
    </Box>
  );
};

export default InlineTagInput;