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

import { CustomImageViewer, Header, PageWrapper } from 'src/components';

import { API_HOST } from 'src/constants';
import { Colors } from 'src/theme';
import { NAVIGATION_PAGES } from 'src/types';
import { StoreType, storage } from 'src/storage';
import { getImageUri, itemWidth } from '../utils';
import { styles } from './styles';

import { useGetMorePhotosQuery } from '@api/events';

const AllEventPhotosScreen = ({ route }: { route: any }) => {
  const { data, eventId, lastPhotoId, photosCountLeft } = route.params;
  const token = storage.get('token', StoreType.STRING) as string;
  const navigation = useNavigation();
  const [lastId, setLastId] = useState(lastPhotoId);
  const [photosLeft, setPhotosLeft] = useState(photosCountLeft);
  const { data: morePhotos } = useGetMorePhotosQuery(
    token,
    eventId,
    lastId,
    photosLeft > 0 ? true : false
  );

  const [photos, setPhotos] = useState<any[]>(data);
  const [fullImages, setFullImages] = useState<any[]>([]);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [modalState, setModalState] = useState({
    isViewerVisible: false
  });

  useEffect(() => {
    setFullImages(
      photos
        .filter((p: any) => p.data)
        .map((photo: any) => ({
          ...photo,
          uri: API_HOST + '/webapi/events/get-photo/' + eventId + '/' + photo.id
        }))
    );
    setLastId(photos[photos.length - 1].id);
  }, [photos]);

  useEffect(() => {
    if (morePhotos && morePhotos.photos) {
      setPhotos((prev) => [...prev, ...morePhotos.photos]);
      setPhotosLeft(morePhotos.photos_left);
    }
  }, [morePhotos]);

  const openImageViewer = (index: number) => {
    setCurrentImageIndex(index);
    openModal('isViewerVisible');
  };

  const renderItem = ({ item, index }: { item: any; index: number }) => (
    <View style={{ alignItems: 'center', marginVertical: 8 }}>
      <TouchableOpacity style={{ position: 'relative' }} onPress={() => openImageViewer(index)}>
        <Image
          source={{
            uri: getImageUri('/webapi/events/get-photo-preview/' + eventId + '/' + item.id)
          }}
          style={[styles.image, { width: itemWidth, height: itemWidth }]}
        />
      </TouchableOpacity>
    </View>
  );

  const closeModal = (modalName: string) => {
    setModalState((prevState) => ({ ...prevState, [modalName]: false }));
  };

  const openModal = (modalName: string) => {
    setModalState((prevState) => ({ ...prevState, [modalName]: true }));
  };

  return (
    <PageWrapper style={{ position: 'relative' }}>
      <Header label={'Photos'} />

      <FlatList
        data={photos}
        renderItem={renderItem}
        keyExtractor={(item) => item.id.toString()}
        numColumns={2}
        columnWrapperStyle={styles.columnWrapper}
        showsVerticalScrollIndicator={false}
      />

      <CustomImageViewer
        images={fullImages}
        imageIndex={currentImageIndex}
        visible={modalState.isViewerVisible}
        onRequestClose={() => closeModal('isViewerVisible')}
        backgroundColor={Colors.DARK_BLUE}
        renderFooter={(imageIndex: number) => (
          <View style={styles.imageFooter}>
            <TouchableOpacity
              onPress={() => {
                closeModal('isViewerVisible');
                navigation.navigate(
                  ...([
                    NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW,
                    { userId: fullImages[imageIndex].uid }
                  ] as never)
                );
              }}
              disabled={!fullImages[imageIndex].uid}
              style={styles.imageOwner}
            >
              {fullImages[imageIndex].avatar ? (
                <Image
                  source={{ uri: API_HOST + fullImages[imageIndex].avatar }}
                  style={{
                    width: 28,
                    height: 28,
                    borderRadius: 14
                  }}
                />
              ) : null}
              <Text style={styles.imageOwnerText}>{fullImages[imageIndex].name}</Text>
            </TouchableOpacity>
          </View>
        )}
      />
    </PageWrapper>
  );
};

export default AllEventPhotosScreen;
