import React, { useRef } from "react";
import { TouchableOpacity, TouchableOpacityProps } from "react-native";
import { Platform_Android } from "../commons";
import { Styled, StyledProps } from "./Styled";

export type TouchableProps = StyledProps &
  TouchableOpacityProps & {
    area?: number;
    shadow?: boolean;
    debounce?: boolean;
    children?: any;
    onPress?: () => void;
    onDoublePress?: () => void;
  };

const DELAY_TIME = 300;

export const Touchable = (props: TouchableProps) => {
  const { area, shadow, debounce, children, onPress, onDoublePress } = props;

  const timer = useRef<any>(false);
  const firstPress = useRef(true);
  const disablePress = useRef(false);
  const lastTime = useRef(new Date().valueOf());

  const _onPress = () => {
    onPress?.();
  };

  const handleSinglePress = () => {
    if (!debounce) _onPress();
    else if (!disablePress.current) {
      _onPress();
      disablePress.current = true;
      const timeout = setTimeout(() => {
        disablePress.current = false;
        clearTimeout(timeout);
      }, 1000);
      return timeout;
    }
  };

  const handleDoublePress = () => {
    const now = new Date().valueOf();
    if (firstPress.current) {
      firstPress.current = false;
      timer.current = setTimeout(() => {
        handleSinglePress();
        firstPress.current = true;
        timer.current = false;
      }, DELAY_TIME);
      lastTime.current = now;
    } else {
      if (now - lastTime.current < DELAY_TIME) {
        timer.current && clearTimeout(timer.current);
        onDoublePress!();
        firstPress.current = true;
      }
    }
  };

  return (
    <Styled {...props}>
      {(style: any) => (
        <TouchableOpacity
          activeOpacity={shadow && Platform_Android ? 1 : 0.85}
          {...props}
          hitSlop={{
            top: area,
            left: area,
            right: area,
            bottom: area,
          }}
          style={style}
          onPress={onDoublePress ? handleDoublePress : handleSinglePress}
        >
          {children}
        </TouchableOpacity>
      )}
    </Styled>
  );
};
