import React, { PropsWithChildren, useRef } from 'react';
import { Animated, StyleSheet, Text, View } from 'react-native';
import { RectButton, Swipeable } from 'react-native-gesture-handler';
import { Colors } from 'src/theme';
import { getFontSize } from 'src/utils';

import { Blocked } from '../types';
import { usePostSetBlockMutation } from '@api/chat';
import BanIcon from 'assets/icons/messages/ban.svg';

interface AppleStyleSwipeableRowProps extends PropsWithChildren<unknown> {
  data: Blocked;
  token: string;
  onRowOpen: (ref: any) => void;
  refetchBlocked: () => void;
}

const SwipeableBlockedRow: React.FC<AppleStyleSwipeableRowProps> = ({
  children,
  data,
  token,
  onRowOpen,
  refetchBlocked
}) => {
  const swipeableRow = useRef<Swipeable>(null);
  const { mutateAsync: unBlockUser } = usePostSetBlockMutation();

  const close = () => {
    swipeableRow.current?.close();
  };

  const renderRightAction = (
    text: string,
    color: string,
    x: number,
    progress: Animated.AnimatedInterpolation<number>
  ) => {
    const trans = progress.interpolate({
      inputRange: [0, 1],
      outputRange: [x, 0]
    });

    const pressHandler = async () => {
      close();
      await unBlockUser({
        token,
        value: 0,
        conversation_with_user: data.id
      });
      refetchBlocked();
    };

    return (
      <Animated.View style={{ flex: 1, transform: [{ translateX: trans }] }}>
        <RectButton style={[styles.rightAction, { backgroundColor: color }]} onPress={pressHandler}>
          <BanIcon height={18} width={18} fill={Colors.WHITE} />
          <Text style={styles.actionText}>{text}</Text>
        </RectButton>
      </Animated.View>
    );
  };

  const renderRightActions = (progress: Animated.AnimatedInterpolation<number>) => (
    <View
      style={{
        width: 84,
        flexDirection: 'row'
      }}
    >
      {renderRightAction('Unblock', Colors.RED, 84, progress)}
    </View>
  );

  return (
    <Swipeable
      ref={swipeableRow}
      friction={2}
      enableTrackpadTwoFingerGesture
      rightThreshold={40}
      renderRightActions={renderRightActions}
      onSwipeableOpenStartDrag={() => {
        onRowOpen(swipeableRow.current);
      }}
    >
      {children}
    </Swipeable>
  );
};

const styles = StyleSheet.create({
  actionText: {
    color: Colors.WHITE,
    fontSize: getFontSize(12),
    fontWeight: '600',
    backgroundColor: 'transparent'
  },
  rightAction: {
    alignItems: 'center',
    flex: 1,
    justifyContent: 'center',
    gap: 8
  }
});

export default SwipeableBlockedRow;
