import React, { useState, useRef } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Animated,
  Pressable,
  Dimensions,
} from 'react-native';

const { width: SCREEN_WIDTH } = Dimensions.get('window');

// COMPONENT: FAB Group với menu mở rộng
const FABGroup = ({
  position = 'bottom-right',
  mainIcon = '+',
  mainBackgroundColor = '#007AFF',
  mainColor = '#FFFFFF',
  size = 'medium',
  actions = [], // Mảng các action buttons
  overlayColor = 'rgba(0, 0, 0, 0.3)',
  animationDuration = 200,
  spacing = 10,
  style,
}) => {
  // STATE: Quản lý trạng thái mở/đóng
  const [isOpen, setIsOpen] = useState(false);
  
  // ANIMATION: Animation values
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const rotateAnim = useRef(new Animated.Value(0)).current;
  const scaleAnim = useRef(new Animated.Value(1)).current;

  // FUNCTIONALITY: Toggle FAB Group
  const toggleFAB = () => {
    const toValue = isOpen ? 0 : 1;
    setIsOpen(!isOpen);

    // ANIMATION: Parallel animations cho smooth effect
    Animated.parallel([
      // Fade overlay
      Animated.timing(fadeAnim, {
        toValue,
        duration: animationDuration,
        useNativeDriver: true,
      }),
      // Rotate main FAB
      Animated.timing(rotateAnim, {
        toValue,
        duration: animationDuration,
        useNativeDriver: true,
      }),
    ]).start();
  };

  // FUNCTIONALITY: Xử lý press action item
  const handleActionPress = (action) => {
    // Close FAB group trước
    toggleFAB();
    
    // Delay để animation hoàn thành rồi mới trigger action
    setTimeout(() => {
      if (action.onPress) {
        action.onPress();
      }
    }, animationDuration / 2);
  };

  // FUNCTIONALITY: Press effects cho main FAB
  const handleMainPressIn = () => {
    Animated.spring(scaleAnim, {
      toValue: 0.95,
      useNativeDriver: true,
    }).start();
  };

  const handleMainPressOut = () => {
    Animated.spring(scaleAnim, {
      toValue: 1,
      friction: 3,
      tension: 40,
      useNativeDriver: true,
    }).start();
  };

  // UI/UX: Tính toán styles
  const fabSize = getFABSize(size);
  const positionStyle = getPositionStyle(position);
  
  // ANIMATION: Rotation cho main icon
  const rotateInterpolate = rotateAnim.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '45deg'], // Xoay 45 độ khi mở
  });

  return (
    <>
      {/* OVERLAY: Background overlay khi mở */}
      {isOpen && (
        <Animated.View
          style={[
            styles.overlay,
            {
              opacity: fadeAnim,
            },
          ]}
        >
          <Pressable 
            style={styles.overlayPressable} 
            onPress={toggleFAB}
          />
        </Animated.View>
      )}

      {/* ACTIONS: Render action buttons */}
      {isOpen && actions.map((action, index) => {
        // ANIMATION: Stagger animation cho từng action
        const actionScale = fadeAnim.interpolate({
          inputRange: [0, 1],
          outputRange: [0, 1],
        });
        
        const actionTranslateY = fadeAnim.interpolate({
          inputRange: [0, 1],
          outputRange: [0, -(fabSize + spacing) * (index + 1)],
        });

        return (
          <Animated.View
            key={action.id || index}
            style={[
              styles.actionContainer,
              positionStyle,
              {
                transform: [
                  { scale: actionScale },
                  { translateY: actionTranslateY },
                ],
                marginBottom: 30, // Offset để không đè lên main FAB
            },
            ]}
          >
            {/* ACTION: Label text */}
            <View style={styles.actionLabelContainer}>
              <View style={styles.actionLabel}>
                <Text style={styles.actionLabelText}>
                  {action.label}
                </Text>
              </View>
            </View>

            {/* ACTION: Button */}
            <Pressable
              style={[
                styles.actionButton,
                {
                  width: fabSize * 0.8, // Nhỏ hơn main FAB một chút
                  height: fabSize * 0.8,
                  borderRadius: (fabSize * 0.8) / 2,
                  backgroundColor: action.backgroundColor || '#FFFFFF',
                },
              ]}
              onPress={() => handleActionPress(action)}
            >
              <Text style={[
                styles.actionIcon,
                {
                  color: action.color || '#333333',
                  fontSize: getFontSize(size) * 0.8,
                }
              ]}>
                {action.icon}
              </Text>
            </Pressable>
          </Animated.View>
        );
      })}

      {/* MAIN FAB: Button chính */}
      <Animated.View
        style={[
          styles.mainFABContainer,
          positionStyle,
          {
            transform: [
              { scale: scaleAnim },
              { rotate: rotateInterpolate },
            ],
          },
          style,
        ]}
      >
        <Pressable
          onPress={toggleFAB}
          onPressIn={handleMainPressIn}
          onPressOut={handleMainPressOut}
          style={[
            styles.mainFAB,
            {
              width: fabSize,
              height: fabSize,
              borderRadius: fabSize / 2,
              backgroundColor: mainBackgroundColor,
            },
          ]}
        >
          <Text style={[
            styles.mainIcon,
            {
              color: mainColor,
              fontSize: getFontSize(size),
            }
          ]}>
            {mainIcon}
          </Text>
        </Pressable>
      </Animated.View>
    </>
  );
};

// FUNCTIONALITY: Lấy kích thước FAB theo size
const getFABSize = (size) => {
  switch (size) {
    case 'small':
      return 40;
    case 'medium':
      return 56;
    case 'large':
      return 72;
    default:
      return 56;
  }
};

// FUNCTIONALITY: Lấy font size theo size
const getFontSize = (size) => {
  switch (size) {
    case 'small':
      return 16;
    case 'medium':
      return 20;
    case 'large':
      return 24;
    default:
      return 20;
  }
};

// FUNCTIONALITY: Lấy style vị trí theo position prop
const getPositionStyle = (position) => {
  const baseStyle = {
    position: 'absolute',
    margin: 15,
  };

  switch (position) {
    case 'bottom-right':
      return { ...baseStyle, bottom: 0, right: 0 };
    case 'bottom-left':
      return { ...baseStyle, bottom: 0, left: 0 };
    case 'top-right':
      return { ...baseStyle, top: 0, right: 0 };
    case 'top-left':
      return { ...baseStyle, top: 0, left: 0 };
    default:
      return { ...baseStyle, bottom: 0, right: 0 };
  }
};

// STYLES: Định nghĩa styles cho component
const styles = StyleSheet.create({
  // OVERLAY: Background overlay
  overlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 999,
  },
  
  overlayPressable: {
    flex: 1,
  },
  
  // MAIN FAB: Container và button chính
  mainFABContainer: {
    zIndex: 1001,
  },
  
  mainFAB: {
    justifyContent: 'center',
    alignItems: 'center',
    elevation: 8,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 4,
    },
    shadowOpacity: 0.3,
    shadowRadius: 8,
  },
  
  mainIcon: {
    fontWeight: 'bold',
    textAlign: 'center',
  },
  
  // ACTION: Container và styles cho action buttons
  actionContainer: {
    zIndex: 1000,
    flexDirection: 'row',
    alignItems: 'center',
  },
  
  actionLabelContainer: {
    marginRight: 12,
  },
  
  actionLabel: {
    backgroundColor: '#FFFFFF',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  
  actionLabelText: {
    color: '#333333',
    fontSize: 14,
    fontWeight: '500',
  },
  
  actionButton: {
    justifyContent: 'center',
    alignItems: 'center',
    elevation: 4,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.2,
    shadowRadius: 4,
  },
  
  actionIcon: {
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

export default FABGroup;