import React, {useCallback} from 'react';
import {View} from 'react-native';
import {GifPreview} from '@components/_custom/GifPreview';
import {LinkPreviewer} from '@components/_custom/LinkPreviewer';
import {Spinner} from '@components/_HuGo';
import {LinkPreviewsBodyParam} from '@interfaces/linkPreview';
import {UserPermissions} from '@interfaces/user';
import {usePermission} from '@redux/selectors';

import {getPostBodyGifProps} from '../../utils';
import {useNewPost} from '../../hooks/useNewPost';
import PollOptions from './components/PollOptions';
import Documents from '../Documents';
import ImagesAndVideos from './components/ImagesAndVideos';
import {styles} from './styles';

interface Props {
  groupId?: number;
}

export function Multimedia({groupId}: Props) {
  const {
    hasPoll,
    messageBody,
    gif,
    linkPreviews,
    isLoading,
    setLinkPreviews,
    setGif,
    initialAttachments,
    post,
  } = useNewPost();
  const requestEdit = !!post?._links?.requestEdit;

  const canCreatePoll = usePermission(UserPermissions.CREATE_POLLS);

  const showPoll = (!!groupId || canCreatePoll) && hasPoll;

  const handleGetLinkPreviews = useCallback(
    (value: LinkPreviewsBodyParam) => {
      if (JSON.stringify(linkPreviews) !== JSON.stringify(value)) {
        setLinkPreviews(value);
      }
    },
    [linkPreviews, setLinkPreviews],
  );

  const handleDeleteGif = () => setGif(null);

  return (
    <View style={styles.multimediaContainer}>
      {isLoading && <Spinner />}
      <LinkPreviewer
        text={messageBody}
        setLinkPreviews={handleGetLinkPreviews}
      />
      <ImagesAndVideos />
      {showPoll && <PollOptions />}
      <Documents />
      {gif && !gif.externalReference?.id && (
        <GifPreview
          gif={gif}
          aspectRatio={gif.aspectRatio}
          onDelete={requestEdit ? undefined : handleDeleteGif}
        />
      )}
      {initialAttachments.initialGif && gif?.externalReference?.id && (
        <GifPreview
          gif={gif.externalReference}
          {...(!requestEdit && {onDelete: handleDeleteGif})}
          {...getPostBodyGifProps(gif)}
        />
      )}
    </View>
  );
}
