import React, { useRef, useState } from 'react';
import { BoxSize, SilkeBox } from '../silke-box';
import { SilkeButtonProps } from '../silke-button';
import { useButtonContext } from '../silke-button/context';
import { SilkeColorSwatchButton } from '../silke-color-swatches';
import { PopoverOrigin, SilkePopover } from '../silke-popover';
import { SilkeColorPicker, SilkeColorPickerProps } from './silke-color-picker';

type SilkeColorPickerButtonProps = {
  anchorOrigin?: PopoverOrigin;
  targetOrigin?: PopoverOrigin;
  children?: React.ReactNode;
} & SilkeColorPickerProps &
  Omit<SilkeButtonProps, 'icon' | 'color' | 'onClick' | 'onChange'>;

export function SilkeColorPickerButton({
  value,
  children,
  hideSwatches,
  hidePalettes,
  noVariables,
  onChange,
  anchorOrigin,
  targetOrigin,
  size,
  noTransparency,
  ...rest
}: SilkeColorPickerButtonProps) {
  const context = useButtonContext();
  const ref = useRef<HTMLButtonElement>(null);
  const [open, setOpen] = useState(false);
  const buttonSize = size || context.size || 'base';

  return (
    <>
      <SilkeColorSwatchButton
        {...rest}
        ref={ref}
        size={buttonSize}
        kind={rest.kind || 'secondary'}
        value={value}
        onClick={() => setOpen(true)}
      />
      {open && (
        <SilkePopover
          hide={!open}
          anchor={ref}
          contextId="silke-color-picker"
          anchorOrigin={anchorOrigin || 'bottom-left'}
          targetOrigin={targetOrigin || 'top-left'}
          onRequestClose={() => setOpen(false)}
        >
          <SilkeBox bg="neutral-20" pad="s" gap="s" column rounded="small">
            {children}
            <SilkeColorPicker
              value={value}
              hideSwatches={hideSwatches}
              hidePalettes={hidePalettes}
              noVariables={noVariables}
              noTransparency={noTransparency}
              onChange={onChange}
            />
          </SilkeBox>
        </SilkePopover>
      )}
    </>
  );
}
