import React, { useState } from 'react';
import { View, StyleSheet, TouchableOpacity, Text, Image, FlatList } from 'react-native';
import ActionSheet, { SheetManager } from 'react-native-actions-sheet';
import { Colors } from 'src/theme';
import { API_HOST } from 'src/constants';

import { itemWidth } from '../../utils';
import { getFontSize } from 'src/utils';

const PhotosForRegionModal = () => {
  const [data, setData] = useState<any>(null);

  const handleSheetOpen = (payload: any) => {
    setData(payload);
  };

  const renderItem = ({ item }: { item: any }) => (
    <View style={{ alignItems: 'center', marginVertical: 8 }}>
      <TouchableOpacity
        style={{ position: 'relative' }}
        onPress={() => {
          data?.selectPhoto(item);
          SheetManager.hide('photos-for-region-modal');
        }}
      >
        <Image
          source={{
            uri: `${API_HOST}/webapi/photos/${item}/small`
          }}
          style={[styles.image, { width: itemWidth, height: itemWidth }]}
        />
      </TouchableOpacity>
    </View>
  );

  return (
    <ActionSheet
      id="photos-for-region-modal"
      containerStyle={styles.sheetContainer}
      defaultOverlayOpacity={0.5}
      closeOnTouchBackdrop={true}
      keyboardHandlerEnabled={true}
      onBeforeShow={(sheetRef) => {
        const payload = sheetRef || null;
        handleSheetOpen(payload);
      }}
    >
      <View style={styles.container}>
        <View style={styles.header}>
          <TouchableOpacity
            style={{
              paddingTop: 16,
              paddingBottom: 6,
              paddingHorizontal: 6
            }}
            onPress={() => {
              SheetManager.hide('photos-for-region-modal');
            }}
          >
            <Text style={styles.cancelText}>Cancel</Text>
          </TouchableOpacity>
        </View>

        {data?.photos?.length > 0 && (
          <FlatList
            data={data.photos}
            renderItem={renderItem}
            keyExtractor={(item) => item.toString()}
            numColumns={2}
            columnWrapperStyle={styles.columnWrapper}
            showsVerticalScrollIndicator={false}
          />
        )}
      </View>
    </ActionSheet>
  );
};

const styles = StyleSheet.create({
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  cancelText: {
    color: Colors.DARK_BLUE,
    fontSize: getFontSize(14),
    fontWeight: '700'
  },
  columnWrapper: {
    justifyContent: 'space-between'
  },
  image: {
    borderRadius: 8
  },
  container: {
    backgroundColor: 'white',
    gap: 16,
    height: '100%'
  },
  sheetContainer: {
    height: '95%',
    borderTopLeftRadius: 15,
    borderTopRightRadius: 15,
    paddingHorizontal: 16
  }
});

export default PhotosForRegionModal;
