import React from 'react';
import {
  ActivityIndicator,
  Image,
  ImageSourcePropType,
  ImageStyle,
  StyleSheet,
  TextStyle,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import { useApi, useMessageItemPopover, useStyles } from '../../hooks';
import { ComponentStyleProp, LLComponentStyleFn } from '../../types';
import { LLText } from '../LLText';

export type LLChatMessageMenuOptionStyles = {
  menuItem: ViewStyle;
  menuItemText: TextStyle;
  menuItemIcon: ImageStyle;
  menuItemTopDivider: ViewStyle;
  menuItemBottomDivider: ViewStyle;
};

export type LLChatMessageMenuOptionProps<
  OnClickApiFnResponseData extends Promise<any>,
> = ComponentStyleProp<LLChatMessageMenuOptionStyles> & {
  icon: ImageSourcePropType;
  textDesc: string;
  divider?: Partial<{
    top: boolean;
    bottom: boolean;
  }>;
  onClickApiFn: () => OnClickApiFnResponseData;
};

export function LLChatMessageMenuOption<
  OnClickApiFnResponseData extends Promise<any>,
>({
  icon,
  textDesc,
  divider = {},
  onClickApiFn,
  styles: stylesProp,
}: LLChatMessageMenuOptionProps<OnClickApiFnResponseData>) {
  const { isLoading, onApi: onClick } =
    useApi<OnClickApiFnResponseData>(onClickApiFn);
  const menuItemStyles = useStyles({
    componentStylesFn: getChatMessageMenuOptionStyles,
    stylesProp,
  });
  const { hidePopover } = useMessageItemPopover();

  return (
    <>
      {divider.top && <View style={menuItemStyles.menuItemTopDivider} />}
      <TouchableOpacity onPress={() => onClick().finally(hidePopover)}>
        <View style={menuItemStyles.menuItem}>
          {isLoading ? (
            <ActivityIndicator
              size="small"
              style={menuItemStyles.menuItemIcon}
            />
          ) : (
            <Image style={menuItemStyles.menuItemIcon} source={icon} />
          )}
          <LLText style={menuItemStyles.menuItemText}>{textDesc}</LLText>
        </View>
      </TouchableOpacity>
      {divider.bottom && <View style={menuItemStyles.menuItemBottomDivider} />}
    </>
  );
}

const getChatMessageMenuOptionStyles: LLComponentStyleFn<
  LLChatMessageMenuOptionStyles
> = ({ theme }) =>
  StyleSheet.create({
    menuItem: {
      flexDirection: 'row',
      justifyContent: 'flex-start',
      alignItems: 'center',
      height: 45,
      padding: 5,
    },
    menuItemText: {
      color: theme.text,
    },
    menuItemIcon: {
      height: 18,
      width: 18,
      marginRight: 10,
    },
    menuItemTopDivider: {
      borderTopWidth: 1,
      borderTopColor: theme.border,
    },
    menuItemBottomDivider: {
      borderBottomWidth: 1,
      borderBottomColor: theme.border,
    },
  });
