import React, { useEffect, useState } from 'react';
import { StyleSheet, Keyboard } from 'react-native';
import { FAB } from 'react-native-paper';
import { ParamListBase, useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useDimensions } from '../contexts';

const styles = StyleSheet.create({
  fab: {
    position: 'absolute',
  },
});

const FloatingActionButton = ({ visible = true }: { visible?: boolean }) => {
  const { navigate } =
    useNavigation<NativeStackNavigationProp<ParamListBase>>();
  const dimensions = useDimensions();

  const [state, setState] = useState(false);
  const [keyboardOpen, setKeyboardOpen] = useState(false);
  useEffect(() => {
    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      () => setKeyboardOpen(true),
    );
    const keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      () => setKeyboardOpen(false),
    );

    return () => {
      keyboardDidHideListener.remove();
      keyboardDidShowListener.remove();
    };
  }, []);

  return (
    <FAB.Group
      open={state}
      visible={visible && !keyboardOpen}
      icon={state ? 'image' : 'plus'}
      actions={[
        {
          icon: 'tag',
          label: 'Tag',
          onPress: () => navigate('Add Tag'),
        },
        {
          icon: 'note-text',
          label: 'Text',
          onPress: () => navigate('Add Meme'),
        },
        {
          icon: 'image-album',
          label: 'Album',
          onPress: () => navigate('Add Meme'),
        },
      ]}
      onStateChange={({ open }) => setState(open)}
      onPress={() => {
        if (state) navigate('Add Meme');
      }}
      style={[
        styles.fab,
        {
          paddingRight: dimensions.responsive.horizontalScale(10),
          paddingBottom: dimensions.responsive.verticalScale(75),
        },
      ]}
    />
  );
};

export default FloatingActionButton;
