import React, {ReactNode} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {StackActions, useNavigation} from '@react-navigation/native';
import {IconChartBar, IconDots, IconPinned} from '@tabler/icons-react-native';
import {Typography, IconButton, ListRow} from '@components';
import {ListItemAvatarProps} from '@components/_HuGo/List/interfaces';
import {avatarIsValid} from '@components/_HuGo/List/utils';
import {DraftUser} from '@interfaces/user';
import {Post} from '@modules/post/interfaces';
import {PostStreamStatus} from '@modules/livestream/interfaces';
import {usePostIsPinned} from '@modules/post/store/useFeedStore';
import {useUserId} from '@redux/selectors';
import {Screens} from '@shared/constants';
import {getCompleteName, getTimeAgo} from '@shared/utils';
import {useTheme} from '@shared/theme';
import {useCommunityFeature} from '@stores/communityFeatures';

import {BasePost} from '../../interfaces';
import {styles} from './styles';

export interface PostHeaderProps {
  onPressOptions?: (post: BasePost) => void;
  post: BasePost;
  withOptions?: boolean;
  creatorUser?: DraftUser;
  renderDescription?: () => ReactNode;
  TitleComponent?: ReactNode;
  TitleRightComponent?: ReactNode;
  isPreviewPost?: boolean;
  isGroupPostInFeed?: boolean;
  canManagePosts?: boolean;
  isInsightsQuickLinkEnabled?: boolean;
  groupId?: number;
}

export function PostHeader({
  onPressOptions,
  post,
  withOptions,
  creatorUser,
  renderDescription,
  TitleComponent,
  TitleRightComponent,
  isPreviewPost,
  isGroupPostInFeed,
  canManagePosts,
  isInsightsQuickLinkEnabled = false,
  groupId,
}: PostHeaderProps) {
  const {t} = useTranslation();
  const {id, publicationDatetime, createdAt, user, stream} = post;
  const navigation = useNavigation();
  const name = getCompleteName(user);
  const postDate = getTimeAgo(publicationDatetime || createdAt);
  const {theme, iconSizes} = useTheme();
  const isPinned = usePostIsPinned(id);
  const userId = useUserId();
  const isOwner = userId === post?.user.id;
  const canViewStats = useCommunityFeature('VIEW_POST_STATS');
  const avatar: ListItemAvatarProps = {
    name,
    url: user.profilePicture,
    id: user.id,
    borderVariant: stream?.status === PostStreamStatus.Live ? 'live' : 'none',
  };

  const creatorAvatar: ListItemAvatarProps | undefined = creatorUser
    ? {
        name: getCompleteName(creatorUser),
        url: creatorUser.profilePicture,
        id: creatorUser.id,
      }
    : undefined;

  const showAvatar = avatarIsValid(avatar);
  const showCreatorAvatar = !!creatorAvatar && avatarIsValid(creatorAvatar);

  const onOptionsPress = () => {
    onPressOptions?.(post);
  };

  const onUserPress = () => {
    navigation.dispatch(StackActions.push(Screens.PROFILE, {userId: user.id}));
  };

  const onPressRow = (post as Post).isExternal ? undefined : onUserPress;

  const title = showCreatorAvatar
    ? `${creatorAvatar?.name} ${t('drafts.steps.post.in_the_name_of')} ${name}`
    : name;

  const onInsightsPress = () => {
    navigation.navigate(Screens.INSIGHTS, {
      id: post.id,
      groupId: groupId || post.group?.id,
    });
  };

  return (
    <ListRow
      onPress={onPressRow}
      disabled={!onPressRow}
      style={[
        styles.listItem,
        styles.listRowPadding,
        showCreatorAvatar && styles.alignTop,
      ]}>
      {showAvatar &&
        (showCreatorAvatar ? (
          <ListRow.AvatarGroup list={[creatorAvatar, avatar]} />
        ) : (
          <ListRow.Avatar {...avatar} />
        ))}
      <View style={styles.flex}>
        {TitleComponent ? (
          <>
            {TitleComponent}
            {renderDescription ? (
              renderDescription()
            ) : (
              <Typography
                variant="xs"
                color={theme.text.neutral.lighter}
                numberOfLines={1}>
                {postDate}
              </Typography>
            )}
          </>
        ) : (
          <ListRow.Title
            title={title}
            titleNumberOfLines={showCreatorAvatar ? 2 : 1}
            renderDescription={renderDescription}
            description={renderDescription ? undefined : postDate}
          />
        )}
      </View>
      {!isPreviewPost && (isPinned || post.pinned) && (
        <IconPinned
          size={iconSizes.x6}
          color={theme.graphics.error[600]}
          style={styles.pinnedIcon}
        />
      )}
      {TitleRightComponent}
      {withOptions && (
        <View style={styles.optionsContainer}>
          {canViewStats &&
            !isGroupPostInFeed &&
            isInsightsQuickLinkEnabled &&
            (!!canManagePosts || isOwner) && (
              <IconButton
                hitSlop={16}
                Icon={IconChartBar}
                onPress={onInsightsPress}
                variant="flat"
                iconColor={theme.text.neutral.default}
              />
            )}
          <IconButton
            hitSlop={16}
            Icon={IconDots}
            onPress={onOptionsPress}
            variant="flat"
            iconColor={theme.text.neutral.default}
          />
        </View>
      )}
    </ListRow>
  );
}
