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 BanIcon from 'assets/icons/messages/ban.svg';
import { database } from 'src/watermelondb';
import { BlockedUser } from 'src/watermelondb/models';
import { Q } from '@nozbe/watermelondb';
import {
  addDirtyAction,
  syncChatsIncremental
} from 'src/watermelondb/features/chat/data/chat.sync';

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

async function findChatRecord(userId: number) {
  const blocked = database.get<BlockedUser>('blocked_users');

  const query = Q.where('user_id', userId);

  const found = await blocked.query(query).fetch();
  return found[0] ?? null;
}

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

  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();
      const rec = await findChatRecord(data.userId);
      if (!rec) return;

      await database.write(() =>
        rec.update((r) => {
          r.removed = true;
          addDirtyAction(r, { type: 'unblock' });
        })
      );

      await syncChatsIncremental(token);
    };

    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;
