import React, {useCallback, useMemo} from 'react';
import DraggableFlatList, {
  DragEndParams,
  RenderItemParams,
} from 'react-native-draggable-flatlist';
import {useNewPost} from '@components/_custom/NewPost/hooks/useNewPost';
import PreviewAttachment from '@components/_custom/PreviewAttachment';
import {Attachment, AttachmentType} from '@interfaces/attachments';
import {sizeToBytes} from '@shared/utils/files';

import {styles} from './styles';

const keyExtractor = (item: Attachment) => item.url;

function ImagesAndVideos() {
  const {videos, images, setImages, setVideos, setCurrentSize, post} =
    useNewPost();
  const requestEdit = !!post?._links?.requestEdit;
  const attachments = useMemo(
    () =>
      [...images, ...videos].sort(
        (a, b) => (a.position || 0) - (b.position || 0),
      ),
    [images, videos],
  );

  const handleDelete = useCallback(
    (attachment: Attachment) => () => {
      if (attachment.type === AttachmentType.IMAGE) {
        setImages(prevImages =>
          prevImages.filter(image => image.url !== attachment.url),
        );
      } else {
        setVideos(prevVideos =>
          prevVideos.filter(video => video.url !== attachment.url),
        );
      }
      setCurrentSize(prev => prev - sizeToBytes(attachment.size));
    },
    [setCurrentSize, setImages, setVideos],
  );

  const renderItem = useCallback(
    ({item, drag}: RenderItemParams<Attachment>) => (
      <PreviewAttachment
        {...item}
        {...(!requestEdit && {onDelete: handleDelete(item), drag})}
      />
    ),
    [handleDelete, requestEdit],
  );

  const onDragEnd = useCallback(
    ({data}: DragEndParams<Attachment>) => {
      const reindexed = data.map((item, index) => ({...item, position: index}));
      const newImages = reindexed.filter(
        item => item.type === AttachmentType.IMAGE,
      );
      const newVideos = reindexed.filter(
        item => item.type === AttachmentType.VIDEO,
      );
      setImages(newImages);
      setVideos(newVideos);
    },
    [setImages, setVideos],
  );

  return attachments.length ? (
    <DraggableFlatList
      data={attachments}
      keyExtractor={keyExtractor}
      renderItem={renderItem}
      onDragEnd={onDragEnd}
      horizontal
      contentContainerStyle={styles.container}
      showsHorizontalScrollIndicator={false}
    />
  ) : null;
}

export default ImagesAndVideos;
