import React from 'react';
import { View, TouchableOpacity, StyleSheet, Dimensions, ActivityIndicator } from 'react-native';
import { Image as ExpoImage } from 'expo-image';
import { MaterialCommunityIcons } from '@expo/vector-icons';

import { useAppColors, spacing, borderRadius } from '../../../theme';
import type { ImageBlock } from './blockEditorTypes';

const SCREEN_WIDTH = Dimensions.get('window').width;
const IMAGE_MAX_WIDTH = SCREEN_WIDTH - 32;

interface ImageBlockViewProps {
  block: ImageBlock;
  onRemove: (blockId: string) => void;
  style?: any;
}

const ImageBlockView: React.FC<ImageBlockViewProps> = ({ block, onRemove, style }) => {
  const colors = useAppColors();

  const aspectRatio = block.width && block.height
    ? block.width / block.height
    : 4 / 3;
  const displayWidth = IMAGE_MAX_WIDTH;
  const displayHeight = displayWidth / aspectRatio;

  const imageSource = block.remoteUrl
    ? { uri: block.remoteUrl }
    : { uri: block.localUri };

  return (
    <View style={[styles.container, style]}>
      <ExpoImage
        source={imageSource}
        style={{
          width: displayWidth,
          height: displayHeight,
          borderRadius: borderRadius.md,
        }}
        contentFit="cover"
        cachePolicy="memory-disk"
        transition={200}
      />
      {block.uploading && (
        <View style={styles.uploadingOverlay}>
          <ActivityIndicator size="small" color={colors.text.inverse} />
        </View>
      )}
      <TouchableOpacity
        style={styles.removeButton}
        onPress={() => onRemove(block.id)}
        hitSlop={{ top: 10, right: 10, bottom: 10, left: 10 }}
      >
        <View style={styles.removeButtonInner}>
          <MaterialCommunityIcons name="close" size={14} color={colors.text.inverse} />
        </View>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    marginTop: 4,
    marginBottom: 0,
    position: 'relative',
    alignItems: 'center',
  },
  uploadingOverlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: borderRadius.md,
  },
  removeButton: {
    position: 'absolute',
    top: 8,
    right: 8 + (SCREEN_WIDTH - IMAGE_MAX_WIDTH) / 2,
    zIndex: 10,
  },
  removeButtonInner: {
    width: 24,
    height: 24,
    borderRadius: borderRadius.full,
    backgroundColor: 'rgba(0, 0, 0, 0.6)',
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default ImageBlockView;