import { useEffect, useRef } from 'react';
import {
  Text,
  TouchableOpacity,
  View,
  Image,
  Animated
} from 'react-native';

import { styles } from './style';

interface Region {
  id: number;
  name: string;
  region_photos: string;
  visitors_count: number;
}

interface RegionPopupProps {
  region: Region;
  userAvatars: string[];
  onMarkVisited: () => void;
}

const RegionPopup: React.FC<RegionPopupProps> = ({ region, userAvatars, onMarkVisited }) => {
  const fadeAnim = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 300,
      useNativeDriver: true,
    }).start();
  }, [fadeAnim]);
  
  const splitRegionName = (fullName: string) => {
    const parts = fullName.split(/ – | - /);
    return {
      regionTitle: parts[0],
      regionSubtitle: parts.length > 1 ? parts[1] : '',
    };
  };

  const { regionTitle, regionSubtitle } = splitRegionName(region.name);
  const regionImg = JSON.parse(region.region_photos)[0];

  function formatNumber(number: number) {
    if (number >= 1000) {
      return (number / 1000).toFixed(1) + 'k';
    }
    return number.toString();
  }
  
  const formattedCount = formatNumber(region.visitors_count);

  return (
    <Animated.View style={[styles.popupContainer, {opacity: fadeAnim}]}>
      <View style={styles.regionInfoContainer}>
        {regionImg && (
          <Image source={{ uri: regionImg}} style={styles.regionImage} />
        )}
        <View style={styles.regionTextContainer}>
          <Text style={styles.regionTitle}>{regionTitle}</Text>
          <Text style={styles.regionSubtitle}>{regionSubtitle}</Text>
        </View>
      </View>

      <View style={styles.separator} />

      <View style={styles.bottomContainer}>
        <View style={styles.userContainer}>
          <View style={styles.userImageContainer}>
            {userAvatars?.map((avatar, index) => (
              <Image
                key={index}
                source={{ uri: avatar }}
                style={styles.userImage}
              />
            ))}
            <View style={styles.userCountContainer}>
              <Text style={styles.userCount}>
                {formattedCount}
              </Text>
            </View>
          </View>
        </View>
        <TouchableOpacity style={styles.markVisitedButton} onPress={onMarkVisited}>
          <Text style={styles.markVisitedText}>
            Mark Visited
          </Text>
        </TouchableOpacity>
      </View>
    </Animated.View>
  );
};

export default RegionPopup;
