import { useState } from 'react';

import type { FC } from 'react';

import useDebounce from '~/src/hooks/useDebounce';
import { isColorLight } from '~/src/lib/utils/color';
import Box from '../Box';
import Card from '../Card';
import CardAction from '../Card/CardAction';
import Text from '../Text';

const ColorPicker: FC<{
  testId?: string;
  isInline?: boolean;
  defaultValue: string | undefined;
  buttonText?: string;
  onChange?(value: string): void;
}> = ({
  testId,
  isInline = false,
  defaultValue = '#000',
  buttonText = 'Change color',
  onChange,
}) => {
  const [internalValue, setInternalValue] = useState(defaultValue);
  const [pickerOpen, setPickerOpen] = useState(false);

  const isLightColor = isColorLight(internalValue);

  const onChangeDebounced = useDebounce(
    ({ target: { value } }) => {
      setInternalValue(value);
      onChange?.(value);
    },
    100,
    [onChange, setInternalValue]
  );

  return (
    <Card
      testId={testId}
      padding="0"
      positionRelative
      pointerEvents={pickerOpen ? 'none' : undefined}
    >
      <Box
        height={isInline ? '5rem' : '8rem'}
        style={{ backgroundColor: internalValue }}
        centerContent
      >
        <Text
          size="1.8rem"
          isBold
          opacity={0.8}
          color={isLightColor ? '#000' : '#fff'}
        >
          {internalValue}
        </Text>
      </Box>
      {!isInline && <CardAction text={buttonText} />}
      <input
        type="color"
        onChange={onChangeDebounced}
        onClick={() => {
          if (!pickerOpen) {
            setPickerOpen(true);
          }
        }}
        onBlur={() => {
          if (pickerOpen) {
            setPickerOpen(false);
          }
        }}
        defaultValue={defaultValue}
        name="backgroundColor"
        style={{
          fontSize: 16,
          opacity: 0,
          position: 'absolute',
          left: 0,
          top: 0,
          width: '100%',
          height: '100%',
          cursor: 'pointer',
          pointerEvents: pickerOpen ? 'none' : 'all',
        }}
      />
    </Card>
  );
};

export default ColorPicker;
