import React from 'react';
import { StyleSheet, useWindowDimensions } from 'react-native';
import { PanGestureHandler } from 'react-native-gesture-handler';
import Animated, {
  useAnimatedGestureHandler,
  useAnimatedStyle,
  useSharedValue,
  withSpring,
} from 'react-native-reanimated';

import {
  FAB_BORDER_RADIUS,
  FAB_WIDTH,
  FAB_MARGIN,
  FAB_STARTING_POSITION,
  LEFT_EDGE_SPACING,
} from './constants';

const FAB = (props) => {
  const { width } = useWindowDimensions();
  const { children } = props;

  // Vị trí drag
  const fabPositionX = useSharedValue(0);
  const fabPositionY = useSharedValue(0);

  // Kéo & snap trái/phải (giữ nguyên logic bạn đang dùng)
  const _onPanHandlerStateChange = useAnimatedGestureHandler({
    onStart: (_, ctx) => {
      ctx.startX = fabPositionX.value;
      ctx.startY = fabPositionY.value;
    },
    onActive: (event, ctx) => {
      fabPositionX.value = ctx.startX + event.translationX;
      fabPositionY.value = ctx.startY + event.translationY;
    },
    onEnd: _ => {
      const SNAP_RIGHT = FAB_STARTING_POSITION; // 0
      const SNAP_LEFT  = -width + FAB_WIDTH + FAB_MARGIN * 2 + LEFT_EDGE_SPACING;

      fabPositionX.value =
        Math.abs(fabPositionX.value - SNAP_LEFT) < Math.abs(fabPositionX.value - SNAP_RIGHT)
          ? withSpring(SNAP_LEFT)
          : withSpring(SNAP_RIGHT);

      // nếu muốn luôn bám dưới, có thể reset Y về 0:
      // fabPositionY.value = withSpring(FAB_STARTING_POSITION);
    },
  });

  const animatedRootStyles = useAnimatedStyle(() => ({
    transform: [
      { translateX: fabPositionX.value },
      { translateY: fabPositionY.value },
    ],
  }));

  return (
    <PanGestureHandler onHandlerStateChange={_onPanHandlerStateChange}>
      <Animated.View style={[styles.rootStyles, animatedRootStyles]}>
        {/* Luôn hiển thị SubButton */}
        <Animated.View style={styles.childrenStyles}>
          {children}
        </Animated.View>
      </Animated.View>
    </PanGestureHandler>
  );
};

export default FAB;

const styles = StyleSheet.create({
  // Neo dưới-phải
  rootStyles: {
    position: 'absolute',
    bottom: 30,
    right: 0,
    borderRadius: FAB_BORDER_RADIUS,
  },
  // Container SubButton (xếp dọc, lệch phải)
  childrenStyles: {
    width: FAB_WIDTH,
    alignItems: 'flex-end',
    marginBottom: 10,
  },
});
