import React, { useEffect, useState } from 'react';
import { 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';
import { ROUTE } from '../types';

const FloatingActionButton = ({ visible = true }: { visible?: boolean }) => {
  const { navigate } =
    useNavigation<NativeStackNavigationProp<ParamListBase>>();
  const { responsive } = 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 () => {
      keyboardDidShowListener.remove();
      keyboardDidHideListener.remove();
    };
  }, []);

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

export default FloatingActionButton;
