import React, { forwardRef, useEffect, useState } from 'react';
import type { RgbaColor } from 'colord';
import { colord } from 'colord';
import type { TextFieldProps } from '@mui/material';
import { CloseRounded } from '@mui/icons-material';

import type { ShapeProp } from '@/mui/types';

import ClickAwayListener from '../../ClickAwayListener/ClickAwayListener';
import IconButton from '../../IconButton/IconButton';
import InputAdornment from '../../InputAdornment/InputAdornment';
import TextField from '../../TextField/TextField';
import ButtonColorPicker from './ButtonColorPicker';

type TextFieldColorPickerProps = {
  value: string;
  disableAlpha?: boolean;
  presetColors?: string[];
  onPickerChange: (color: { hex: string; rgb: RgbaColor }) => void;
  onPickerClear?: () => void;
  onButtonClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
  onClick?: (event: React.MouseEvent<HTMLDivElement>) => void;
  onFocus?: (event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement, Element>) => void;
  onBlur?: (event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement, Element>) => void;
  size?: TextFieldProps['size'];
  shape?: ShapeProp;
  disabled?: boolean;
  disableClearable?: boolean;
};
const TextFieldColorPicker = forwardRef<HTMLDivElement, TextFieldColorPickerProps>((props, ref) => {
  const [value, setValue] = useState(props.value);
  const [open, setOpen] = useState(false);
  const {
    disableAlpha,
    presetColors,
    onPickerChange,
    onButtonClick,
    onPickerClear,
    disableClearable = true,
    ...inputProps
  } = props;

  useEffect(() => {
    setValue(props.value);
  }, [props.value]);

  return (
    <ClickAwayListener onClickAway={() => setOpen(false)}>
      <TextField
        {...inputProps}
        ref={ref}
        value={value}
        onClick={(event) => {
          if (props.onClick) {
            props.onClick(event);
          }
        }}
        onFocus={(event, ...args) => {
          if (props.onFocus) {
            props.onFocus(event, ...args);
          }
          setOpen(true);
        }}
        onChange={(event) => setValue(event.target.value)}
        onBlur={(event, ...args) => {
          if (props.onBlur) {
            props.onBlur(event, ...args);
          }

          const color = colord(event.target.value);
          if (color.isValid()) {
            onPickerChange({
              hex: color.toHex(),
              rgb: color.toRgb(),
            });
          } else {
            setValue(props.value);
          }
        }}
        shape={props.shape}
        size={props.size}
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              {!disableClearable && onPickerClear && (
                <IconButton
                  onClick={() => {
                    onPickerClear();
                  }}
                >
                  <CloseRounded />
                </IconButton>
              )}
              <ButtonColorPicker
                dense="margin"
                size={props.size}
                shape={props.shape}
                disabled={props.disabled}
                disableAlpha={disableAlpha}
                color={value}
                open={open}
                onClick={(event) => {
                  if (onButtonClick) {
                    onButtonClick(event);
                  }
                  setOpen(true);
                }}
                placement="bottom-end"
                onPickerChange={(data) => {
                  setValue(`rgba(${[data.rgb.r, data.rgb.g, data.rgb.b, data.rgb.a].join(',')})`);
                  onPickerChange(data);
                }}
                presetColors={presetColors}
              />
            </InputAdornment>
          ),
        }}
      />
    </ClickAwayListener>
  );
});

TextFieldColorPicker.displayName = 'TextFieldColorPicker';

export default TextFieldColorPicker;
