import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  Platform,
  KeyboardAvoidingView,
  ScrollView,
  Image
} from 'react-native';

import { Button, Input, Modal, FlatList as List } from 'src/components';
import RangeCalendar from 'src/components/Calendars/RangeCalendar';
import { ButtonVariants } from 'src/types/components';

import { AllRegions, PhotosData } from '../utils/types';
import { getImageUri } from '../utils';
import { styles } from './styles';

import ChevronIcon from '../../../../../assets/icons/travels-screens/chevron-bottom.svg';
import CalendarSvg from '../../../../../assets/icons/calendar.svg';

export const PhotoEditModal = ({
  isVisible,
  onClose,
  photo,
  allRegions,
  handleUpdate,
  description,
  setDescription,
  selectedDate,
  setSelectedDate,
  selectedRegion,
  setSelectedRegion
}: {
  isVisible: boolean;
  onClose: () => void;
  photo: PhotosData;
  allRegions: AllRegions[];
  handleUpdate: () => void;
  description: string | null;
  setDescription: (text: string) => void;
  selectedDate: string | null;
  setSelectedDate: (date: string) => void;
  selectedRegion: AllRegions | null;
  setSelectedRegion: (region: any) => void;
}) => {
  const [imgAspectRatio, setImgAspectRatio] = useState(0);
  const [isRegionsModalVisible, setIsRegionsModalVisible] = useState(false);
  const [calendarVisible, setCalendarVisible] = useState(false);

  useEffect(() => {
    if (photo) {
      const uri = getImageUri(photo.url_mid);
      Image.getSize(
        uri,
        (width, height) => {
          const aspectRatio = width / height;
          setImgAspectRatio(aspectRatio);
        },
        (error) => {
          console.error(`Couldn't get the image size: ${error}`);
        }
      );
    }
  }, [photo]);

  return (
    <Modal visible={isVisible} onRequestClose={onClose} headerTitle="Edit photo">
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={{ flex: 1 }}
        keyboardVerticalOffset={Platform.select({ ios: 44, android: 27 })}
      >
        <ScrollView
          keyboardShouldPersistTaps="handled"
          contentContainerStyle={{ flexGrow: 1 }}
          showsVerticalScrollIndicator={false}
        >
          <Image
            source={{ uri: getImageUri(photo?.url_mid) }}
            style={[
              styles.imageEdit,
              {
                aspectRatio: imgAspectRatio
              }
            ]}
          />
          <View style={{ gap: 10, marginTop: 8 }}>
            <Input
              placeholder="Photo description"
              inputMode={'text'}
              onChange={(text) => setDescription(text)}
              value={description ?? photo?.title}
            />
            <TouchableOpacity
              style={[styles.regionSelector, , { justifyContent: 'space-between' }]}
              onPress={() => setIsRegionsModalVisible(true)}
            >
              <Text style={styles.regionText}>
                {selectedRegion?.country ??
                  allRegions.find((region: AllRegions) => region.id === photo?.region)?.country}
              </Text>
              <ChevronIcon />
            </TouchableOpacity>

            <TouchableOpacity
              style={styles.regionSelector}
              onPress={() => setCalendarVisible(true)}
            >
              <CalendarSvg />
              <Text style={styles.regionText}>{selectedDate ?? photo?.date}</Text>
            </TouchableOpacity>

            <RangeCalendar
              isModalVisible={calendarVisible}
              closeModal={(date: Date | null) => {
                date && setSelectedDate(date.toISOString().split('T')[0]);
                setCalendarVisible(false);
              }}
              allowRangeSelection={false}
            />
          </View>
          <View style={styles.saveBtn}>
            <Button variant={ButtonVariants.FILL} onPress={handleUpdate} children={'Save'} />
          </View>

          <Modal
            onRequestClose={() => setIsRegionsModalVisible(false)}
            headerTitle={'Select Region'}
            visible={isRegionsModalVisible}
          >
            <List
              itemObject={(object) => {
                setSelectedRegion(object);
                setIsRegionsModalVisible(false);
              }}
              initialData={allRegions}
            />
          </Modal>
        </ScrollView>
      </KeyboardAvoidingView>
    </Modal>
  );
};
