import React from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Image,
  Animated
} from 'react-native';
import { PuzzleTile as PuzzleTileType } from '../SimplePuzzleGame';

interface PuzzleTileProps {
  tile: PuzzleTileType | null;
  size: number;
  onPress: () => void;
  canMove: boolean;
  useNumbers: boolean;
  imageUrl?: any;
  isEmpty?: boolean;
  animatedValue?: any;
}

/**
 * Individual puzzle tile component with animations
 */
export const PuzzleTileComponent: React.FC<PuzzleTileProps> = ({
  tile,
  size,
  onPress,
  canMove,
  useNumbers,
  imageUrl,
  isEmpty = false,
  animatedValue
}) => {
  // Empty tile
  if (isEmpty) {
    return (
      <View style={[
        styles.tile, 
        styles.emptyTile, 
        { width: size, height: size }
      ]} />
    );
  }

  if (!tile) {
    console.warn('PuzzleTile: No tile provided');
    return null;
  }

  // For image tiles, value can be null
  if (tile.value === undefined) {
    console.warn('PuzzleTile: Tile has undefined value:', tile);
  }

  // Check if tile is in correct position
  const isCorrect = tile.position.row === tile.correctPosition.row && 
                   tile.position.col === tile.correctPosition.col;

  // Animated styles
  const animatedStyle = animatedValue ? {
    transform: [{ scale: animatedValue }]
  } : {};

  const renderTileContent = () => {
    // If we have an image URL, use image sections
    if (imageUrl && !useNumbers) {
      const gridSize = 3; // Assuming 3x3 for now
      const row = tile.correctPosition.row;
      const col = tile.correctPosition.col;
      
      return (
        <View style={[styles.imageTile, { width: size, height: size }]}>
          <Image
            source={imageUrl}
            style={[
              styles.imageSection,
              { 
                width: size * gridSize,
                height: size * gridSize,
                backgroundColor: '#E0E0E0',
                transform: [
                  { translateX: -col * size },
                  { translateY: -row * size }
                ]
              }
            ]}
            resizeMode="cover"
          />
        </View>
      );
    } else {
      // Show numbers as fallback, or empty space if value is null
      if (tile.value !== null) {
        return (
          <Text style={[styles.tileText, { fontSize: size * 0.3 }]}>
            {tile.value}
          </Text>
        );
      } else {
        return (
          <View style={[styles.emptyTileContent, { width: size, height: size }]} />
        );
      }
    }
  };

  return (
    <Animated.View style={animatedStyle}>
      <TouchableOpacity
        style={[
          styles.tile,
          { width: size, height: size },
          canMove && styles.movableTile,
          isCorrect && styles.correctTile,
          !canMove && !isCorrect && styles.lockedTile
        ]}
        onPress={onPress}
        disabled={!canMove}
        activeOpacity={canMove ? 0.7 : 1}
      >
        {renderTileContent()}
        
        {/* Correct position indicator */}
        {isCorrect && (
          <View style={styles.correctIndicator}>
            <Text style={styles.correctIcon}>✓</Text>
          </View>
        )}
        
        {/* Move hint indicator */}
        {canMove && !isCorrect && (
          <View style={styles.moveHint}>
            <Text style={styles.moveHintIcon}>↔</Text>
          </View>
        )}
      </TouchableOpacity>
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  tile: {
    backgroundColor: '#FFF',
    borderRadius: 8,
    margin: 2,
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.15,
    shadowRadius: 4,
    elevation: 4,
    borderWidth: 1,
    borderColor: '#E0E0E0',
  },
  emptyTile: {
    backgroundColor: 'transparent',
    shadowOpacity: 0,
    elevation: 0,
    borderColor: 'transparent',
  },
  movableTile: {
    backgroundColor: '#E3F2FD',
    borderWidth: 2,
    borderColor: '#2196F3',
    shadowColor: '#2196F3',
    shadowOpacity: 0.3,
  },
  correctTile: {
    backgroundColor: '#E8F5E8',
    borderWidth: 2,
    borderColor: '#4CAF50',
    shadowColor: '#4CAF50',
    shadowOpacity: 0.3,
  },
  lockedTile: {
    backgroundColor: '#F5F5F5',
    borderColor: '#BDBDBD',
  },
  tileText: {
    fontWeight: 'bold',
    color: '#333',
    textAlign: 'center',
  },
  imageTile: {
    width: '100%',
    height: '100%',
    borderRadius: 6,
    overflow: 'hidden',
    justifyContent: 'center',
    alignItems: 'center',
  },
  imageSection: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  imageNumber: {
    fontSize: 12,
    fontWeight: 'bold',
    color: '#666',
  },
  emptyTileContent: {
    backgroundColor: 'transparent',
  },
  correctIndicator: {
    position: 'absolute',
    top: 2,
    right: 2,
    width: 16,
    height: 16,
    backgroundColor: '#4CAF50',
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  correctIcon: {
    color: 'white',
    fontSize: 10,
    fontWeight: 'bold',
  },
  moveHint: {
    position: 'absolute',
    bottom: 2,
    right: 2,
    width: 16,
    height: 16,
    backgroundColor: '#2196F3',
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  moveHintIcon: {
    color: 'white',
    fontSize: 8,
    fontWeight: 'bold',
  },
});
