import React from 'react';
import { useAnimatedStyle, useDerivedValue } from 'react-native-reanimated';

import colorKit from '../../colorKit/index';
import usePickerContext from '../../AppContext';
import { styles } from '../../styles';
import BuiltinThumbs from './BuiltinThumbs/index';

import type { BuiltinThumbsProps, ThumbProps } from '../../types';

export default function Thumb({
  thumbAnimatedStyle,
  innerStyle,
  style,
  thumbColor,
  renderThumb: RenderThumb,
  thumbShape = 'ring',
  thumbSize,
  vertical = false,
  overrideHSV,
  getAdaptiveColor,
}: ThumbProps) {
  const { width, height, borderRadius } = { width: thumbSize, height: thumbSize, borderRadius: thumbSize / 2 };
  const { hueValue, saturationValue, brightnessValue, alphaValue, value } = usePickerContext();

  const hue = overrideHSV?.hue ?? hueValue;
  const saturation = overrideHSV?.saturation ?? saturationValue;
  const brightness = overrideHSV?.brightness ?? brightnessValue;
  const alpha = overrideHSV?.alpha ?? alphaValue;

  const currentColor = useDerivedValue(() => {
    return colorKit.runOnUI().HEX({ h: hue.value, s: saturation.value, v: brightness.value });
  }, [hue, saturation, brightness]);

  const solidColor = useAnimatedStyle(() => ({ backgroundColor: thumbColor ?? currentColor.value }), [thumbColor, currentColor]);

  const adaptiveColor = useDerivedValue<string>(() => {
    const currentcolor = {
      h: hue.value,
      s: saturation.value,
      v: brightness.value,
      a: alpha.value,
    };

    const compareColor = getAdaptiveColor?.(currentcolor) || currentcolor;
    const isDark = colorKit.runOnUI().isDark(compareColor);

    return isDark ? '#ffffff' : '#000000';
  }, [hue, saturation, brightness, alpha, getAdaptiveColor]);

  const thumbProps: BuiltinThumbsProps = {
    width,
    height,
    borderRadius,
    vertical,
    solidColor,
    adaptiveColor,
    thumbAnimatedStyle,
    innerStyle,
    style,
    thumbColor,
  };

  // render a custom thumb
  if (RenderThumb) {
    return (
      <RenderThumb
        positionStyle={[styles.handle, thumbAnimatedStyle]}
        width={width}
        height={height}
        initialColor={value}
        currentColor={currentColor}
        adaptiveColor={adaptiveColor}
      />
    );
  }

  // normalize 'thumbShape' string to match 'BuiltinThumbs' keys.
  const thumb_Shape = (thumbShape.toLowerCase().charAt(0).toUpperCase() + thumbShape.slice(1)) as keyof typeof BuiltinThumbs;

  if (thumb_Shape in BuiltinThumbs) {
    const SelectedThumb = BuiltinThumbs[thumb_Shape];
    return <SelectedThumb {...thumbProps} />;
  }

  // default to the 'Ring' thumb
  return <BuiltinThumbs.Ring {...thumbProps} />;
}
