import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { View, Image, Text, TouchableOpacity } from 'react-native';
import { useNavigation } from '@react-navigation/native';

import { getImageUri, photoStyles, smallPhotoHeight, smallPhotoWidth } from '../utils';
import { AllRegions, PhotosData } from '../utils/types';
import { NAVIGATION_PAGES } from 'src/types';
import { styles } from './styles';

import ChevronRightIcon from '../../../../../assets/icons/travels-screens/chevron-right.svg';
import { API_HOST } from 'src/constants';
import { Colors } from 'src/theme';
import { CustomImageViewer } from 'src/components';

export const PhotoItem = React.memo(
  ({ item, allRegions }: { item: any; allRegions: AllRegions[] }) => {
    const navigation = useNavigation();
    const [currentImageIndex, setCurrentImageIndex] = useState(0);
    const [isViewerVisible, setIsViewerVisible] = useState(false);
    const [fullImages, setFullImages] = useState<PhotosData[]>([]);

    const openImageViewer = (index: number) => {
      setCurrentImageIndex(index);
      setIsViewerVisible(true);
    };

    useEffect(() => {
      setFullImages(
        item.photos.map((photo: PhotosData) => ({
          ...photo,
          uri: API_HOST + photo.url_mid
        }))
      );
    }, [item]);

    const renderPhotos = () => {
      const photos = item.photos.slice(0, 3);
      const morePhotosCount = item.photos.length - 3;

      if (photos.length === 1) {
        return (
          <TouchableOpacity onPress={() => openImageViewer(0)}>
            <Image
              source={{ uri: getImageUri(photos[0].url_small), cache: 'reload' }}
              style={photoStyles.onePhoto}
            />
          </TouchableOpacity>
        );
      } else if (photos.length === 2) {
        return photos.map((photo: PhotosData, index: number) => (
          <TouchableOpacity key={photo.id} onPress={() => openImageViewer(index)}>
            <Image
              source={{ uri: getImageUri(photo.url_small), cache: 'reload' }}
              style={[photoStyles.twoPhotos, index === 0 && { marginRight: 8 }]}
            />
          </TouchableOpacity>
        ));
      } else {
        return (
          <View style={{ flexDirection: 'row' }}>
            <TouchableOpacity onPress={() => openImageViewer(0)}>
              <Image
                source={{ uri: getImageUri(photos[0].url_small), cache: 'reload' }}
                style={photoStyles.bigPhoto}
              />
            </TouchableOpacity>

            <View style={styles.smallPhotoContainer}>
              <TouchableOpacity onPress={() => openImageViewer(1)}>
                <Image
                  source={{ uri: getImageUri(photos[1].url_small), cache: 'reload' }}
                  style={photoStyles.smallPhoto}
                />
              </TouchableOpacity>
              <TouchableOpacity onPress={() => openImageViewer(2)}>
                <Image
                  source={{ uri: getImageUri(photos[2].url_small), cache: 'reload' }}
                  style={[photoStyles.smallPhoto, { position: 'relative' }]}
                />
              </TouchableOpacity>
              {morePhotosCount > 0 && (
                <TouchableOpacity
                  onPress={() => openImageViewer(2)}
                  style={[
                    styles.morePhotosOverlay,
                    { width: smallPhotoWidth, height: smallPhotoHeight }
                  ]}
                >
                  <Text style={styles.morePhotosText}>+{morePhotosCount}</Text>
                </TouchableOpacity>
              )}
            </View>
          </View>
        );
      }
    };

    const photoViews = useMemo(() => renderPhotos(), [item.photos]);

    const handlePress = useCallback(() => {
      navigation.navigate(
        ...([
          NAVIGATION_PAGES.MORE_PHOTOS,
          {
            data: item,
            allRegions: allRegions
          }
        ] as never)
      );
    }, [navigation, item]);

    return (
      <View style={styles.listItem}>
        <View style={[styles.listItemHeader, item.date && { alignItems: 'flex-end' }]}>
          {item.date ? (
            <View style={styles.listItemTextContainer}>
              <Text style={styles.listItemTitle}>{item.date}</Text>
            </View>
          ) : (
            <>
              <Image style={styles.flagImg} source={{ uri: getImageUri(item.flag) }} />
              <View style={styles.listItemTextContainer}>
                <Text style={styles.listItemTitle}>{item.country}</Text>
                {item.name && <Text style={styles.listItemSubtitle}>{item.name}</Text>}
              </View>
            </>
          )}
          <TouchableOpacity style={styles.moreButton} onPress={handlePress}>
            <Text style={styles.moreText}>More </Text>
            <ChevronRightIcon />
          </TouchableOpacity>
        </View>
        <View style={styles.photoContainer}>{photoViews}</View>
        <CustomImageViewer
          images={fullImages as any}
          imageIndex={currentImageIndex}
          visible={isViewerVisible}
          onRequestClose={() => setIsViewerVisible(false)}
          backgroundColor={Colors.DARK_BLUE}
        />
      </View>
    );
  }
);
