import { useState, useEffect } from 'react';
import {
  Box,
  TextField,
  Autocomplete,
  Typography,
  Chip,
  Stack,
  FormLabel,
} from '@mui/material';
import ClearIcon from '@mui/icons-material/Clear';

export const AutocompleteForChangeOptions = ({
  values = [],
  options = [],
  onChange,
  placeholder = 'Введите...',
  label = '',
}) => {
  const [selected, setSelected] = useState([]);
  const [available, setAvailable] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [key, setKey] = useState(0);

  useEffect(() => {
    if (values && options) {
      setSelected(values);

      const availableItems = options.filter(
        (allItems) => !values.some((v) => v.id === allItems.id),
      );
      setAvailable(availableItems);
    }
  }, [values, options]);

  const handleSelect = (event, value) => {
    if (value) {
      const newSelected = [...selected, value];
      setSelected(newSelected);
      onChange?.((prev) => ({ ...prev, update: [...prev.update, value] }));

      const newAvailable = available.filter((item) => item.id !== value.id);
      setAvailable(newAvailable);

      setInputValue('');
      setKey((prev) => prev + 1);
    }
  };

  const handleRemove = (id) => {
    const itemToRemove = selected.find((s) => s.id === id);
    if (!itemToRemove) return;

    const newSelected = selected.filter((s) => s.id !== id);
    setSelected(newSelected);
    setAvailable([...available, itemToRemove]);

    const wasInitial = values.some((v) => v.id === id);

    if (wasInitial) {
      onChange?.((prev) => ({
        ...prev,
        delete: [...prev.delete, itemToRemove],
      }));
    } else {
      onChange?.((prev) => ({
        ...prev,
        update: prev.update.filter((u) => u.id !== id),
      }));
    }
  };

  const getDisplayName = (value) => {
    if (value.title) {
      return value.title;
    }
    if (value.full_name) {
      return value.full_name;
    }
    if (value.username) {
      return value.username;
    }
    return value.email;
  };

  return (
    <Box sx={{ width: '100%' }}>
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: '0.125rem' }}>
        <FormLabel
          sx={{
            fontWeight: '400',
            fontSize: '0.75rem',
            color: '#4a5565',
            margin: '0',
          }}
        >
          {label}
        </FormLabel>

        <Autocomplete
          key={key}
          options={available}
          getOptionLabel={(option) => {
            let label = getDisplayName(option);
            if (option.email) {
              label += ` (${option.email})`;
            }
            return label ?? '-';
          }}
          onChange={handleSelect}
          inputValue={inputValue}
          onInputChange={(event, newInputValue, reason) => {
            if (reason === 'input' || reason === 'clear') {
              setInputValue(newInputValue);
            }
          }}
          sx={{ height: '2rem', minWidth: '100%' }}
          renderInput={(params) => (
            <TextField
              {...params}
              placeholder={placeholder}
              sx={{
                height: '2rem',
                width: '100%',
                '& .MuiOutlinedInput-root': {
                  height: '2rem',
                  '& fieldset': {
                    borderRadius: '0.5rem',
                    borderColor: 'rgba(0,0,0,0.1)',
                  },
                  '& input': {
                    padding: '0.25rem 0.75rem',
                    fontSize: '0.875rem',
                  },
                },
              }}
            />
          )}
          renderOption={(props, option) => (
            <li {...props} style={{ padding: '4px 12px', minHeight: '36px' }} key={option.id}>
              <Box
                sx={{
                  display: 'flex',
                  flexDirection: 'column',
                  width: '100%',
                }}
              >
                <Typography variant="body2" sx={{ fontSize: '0.875rem' }}>
                  {getDisplayName(option)}
                </Typography>
                <Typography
                  variant="caption"
                  color="text.secondary"
                  sx={{ fontSize: '0.75rem' }}
                >
                  {option.email}
                </Typography>
                {option.username && (
                  <Typography
                    variant="caption"
                    color="text.secondary"
                    sx={{ fontSize: '0.75rem' }}
                  >
                    Логин: {option.username}
                  </Typography>
                )}
              </Box>
            </li>
          )}
          disableClearable
          fullWidth
          clearOnBlur={false}
          clearOnEscape={false}
        />
      </Box>

      <Box
        sx={{
          minHeight: '5.81rem',
          height: 'max-content',
          marginTop: '1rem',
        }}
      >
        {selected.length > 0 && (
          <Stack
            direction="row"
            spacing={1}
            sx={{ flexWrap: 'wrap', gap: '.5rem', mt: 0 }}
          >
            {selected.map((user) => (
              <Chip
                key={user.id}
                label={getDisplayName(user)}
                onDelete={() => handleRemove(user.id)}
                variant="outlined"
                color="primary"
                size="small"
                deleteIcon={
                  <ClearIcon
                    sx={{
                      fontSize: '.875rem',
                      color: '#323031 !important',
                      height: '.875rem !important',
                      width: '.875rem !important',
                      margin: '0 !important',
                      '&:hover': {
                        color: '#000000',
                      },
                    }}
                  />
                }
                sx={{
                  border: '1px solid rgba(0, 0, 0, 0.1)',
                  borderRadius: '0.5rem',
                  padding: '0 0.25rem 0 0.5rem',
                  height: '1.38rem',
                  color: '#4a5565',
                  display: 'flex',
                  alignItems: 'center',
                  margin: '0 !important',
                  fontSize: '0.75rem',
                  gap: '.57rem',
                  '& .MuiChip-label': {
                    padding: '0',
                    paddingRight: '0.25rem',
                  },
                  '& .MuiChip-deleteIcon': {
                    margin: '0',
                    marginLeft: '0.25rem',
                  },
                }}
              />
            ))}
          </Stack>
        )}
      </Box>

      <Box sx={{ mt: 2, display: 'flex', justifyContent: 'end' }}>
        <Typography variant="caption" color="text.secondary">
          Выбрано: {selected.length}
        </Typography>
      </Box>
    </Box>
  );
};
