import { useState } from 'react';
import { Box, Tooltip } from '@mui/material';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import { Palette } from '../../../common/icons/icons';
import ColorPalette from './ColorPalette';

export const ColorPickerButton = ({
  onColorApply,
  defaultColor = '#C2D59A',
}) => {
  const [isPaletteOpen, setIsPaletteOpen] = useState(false);
  const [color, setColor] = useState(defaultColor);

  const handleColorSelect = (selectedColor) => {
    setColor(selectedColor);
    setIsPaletteOpen(false);
  };

  const handleApplyColor = () => {
    if (onColorApply) {
      onColorApply(color);
    }
  };

  return (
    <div style={{ position: 'relative', height: '100%' }}>
      <Tooltip title="Изменить цвет">
        <Box
          sx={{
            display: 'inline-flex',
            border: '1px solid rgba(0, 0, 0, 0.1)',
            borderRadius: '0.5rem',
            overflow: 'hidden',
            alignItems: 'stretch',
            height: '100%',
          }}
        >
          <Box
            onClick={handleApplyColor}
            sx={{
              width: '2.6rem',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              cursor: 'pointer',
              backgroundColor: 'white',
              '&:hover': {
                backgroundColor: 'rgba(0, 0, 0, 0.04)',
              },
            }}
          >
            <Palette />
          </Box>
          <Box
            onClick={() => {
              setIsPaletteOpen(true);
            }}
            sx={{
              flex: 1,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              cursor: 'pointer',
              backgroundColor:
                color === '#FFFFFF' || color === '#ffffff' || color === null
                  ? 'white'
                  : color || '#C2D59A',
              borderLeft: '1px solid rgba(0, 0, 0, 0.1)',
              padding: '0.5rem',
              width: '1.4rem',
              boxSizing: 'border-box',
              '&:hover': {
                opacity: 0.9,
              },
            }}
          >
            <KeyboardArrowDownIcon
              sx={{ color: '#4A5565', fontSize: '1.25rem' }}
            />
          </Box>
        </Box>
      </Tooltip>

      {isPaletteOpen && (
        <ColorPalette
          onColorSelect={handleColorSelect}
          onClose={() => setIsPaletteOpen(false)}
        />
      )}
    </div>
  );
};
