import React, {memo} from 'react';
import {Image, Pressable, ScrollView, View} from 'react-native';
import {ImageOrVideo} from 'react-native-image-crop-picker';
import {IconPlayerPlayFilled} from '@tabler/icons-react-native';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {useTheme} from '@shared/theme';
import {hexToRgb} from '@shared/colors';

import {styles} from './styles';
import {isImage} from '../../utils';

type PropsThumbs = {
  assets: ImageOrVideo[];
  activeIndex: number;
  onSelectIndex: (index: number) => void;
  videoThumbs: Record<string, string>;
};

const Thumbs = ({
  assets,
  activeIndex,
  onSelectIndex,
  videoThumbs,
}: PropsThumbs) => {
  const {theme, iconSizes} = useTheme();
  const blackTransparent = hexToRgb(theme.black, 0.5);
  const {bottom} = useSafeAreaInsets();

  const onPressThumb = (idx: number) => () => {
    onSelectIndex(idx);
  };

  return (
    <View style={[styles.thumbsBar, {bottom: bottom}]}>
      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={styles.thumbsContent}>
        {assets.map((f, idx) => (
          <Pressable
            key={`${f.path}-${idx}`}
            onPress={onPressThumb(idx)}
            style={[
              styles.thumb,
              idx === activeIndex && styles.thumbSelected,
              {
                backgroundColor: theme.background.layout.default,
                borderColor: theme.brand[500],
              },
            ]}>
            <Image
              source={{uri: isImage(f) ? f.path : videoThumbs[f.path]}}
              style={styles.thumbImage}
            />
            {!isImage(f) ? (
              <View style={styles.playOverlayThumb}>
                <View
                  style={[
                    styles.playCircleSm,
                    {
                      borderColor: theme.background.elements.default,
                      backgroundColor: blackTransparent,
                    },
                  ]}>
                  <IconPlayerPlayFilled
                    color={theme.background.elements.default}
                    fill={theme.background.elements.default}
                    size={iconSizes.x4}
                  />
                </View>
              </View>
            ) : null}
          </Pressable>
        ))}
      </ScrollView>
    </View>
  );
};

export default memo(Thumbs);
