import React, { Dispatch, ReactNode, SetStateAction, useState } from 'react';
import {
  Dimensions,
  Image,
  Modal,
  StyleSheet,
  SafeAreaView,
  TouchableWithoutFeedback,
  ScrollView,
} from 'react-native';
import { Box } from '../Box';
import { TouchableComponent } from '../TouchableComponent';
import { X } from 'phosphor-react-native';

interface ILightBox {
  show: boolean;
  setShow: Dispatch<SetStateAction<boolean>>;
}

export interface WithOutImage extends ILightBox {
  uri?: never;
  body: ReactNode;
}

export interface WithImage extends ILightBox {
  uri: string;
  body?: ReactNode;
}

export const LightBox = ({
  show,
  setShow,
  uri,
  body,
}: WithOutImage | WithImage) => {
  const { width } = Dimensions.get('window');

  return (
    <Modal
      transparent={true}
      visible={show}
      animationType="fade"
      onRequestClose={() => setShow(!show)}
    >
      <Box
        flex={1}
        pointerEvents="box-none"
        style={StyleSheet.absoluteFill}
        collapsable={false}
        justifyContent="flex-end"
        backgroundColor="blackWithOpacity"
      >
        <TouchableWithoutFeedback onPress={() => setShow(false)}>
          <SafeAreaView>
            <TouchableComponent
              alignSelf={'flex-start'}
              backgroundColor={'white'}
              justifyContent="center"
              alignItems={'center'}
              borderRadius={9999}
              height={32}
              width={32}
              m={'spacing-xs'}
              onPress={() => setShow(false)}
              testID="lightBoxCloseButton"
            >
              <X size={16} />
            </TouchableComponent>
          </SafeAreaView>
        </TouchableWithoutFeedback>
        <Box
          flex={1}
          backgroundColor={'white'}
          borderTopLeftRadius={16}
          borderTopRightRadius={16}
        >
          <ScrollView contentContainerStyle={scrollview.container}>
            <Box
              flex={1}
              p="spacing-s"
              alignItems="center"
              justifyContent="center"
            >
              {uri && (
                <RemoteImage {...{ _uri: uri }} _desiredWidth={width - 32} />
              )}
              {body && body}
            </Box>
          </ScrollView>
        </Box>
      </Box>
    </Modal>
  );
};

const RemoteImage = ({
  _uri,
  _desiredWidth,
}: {
  _uri: string;
  _desiredWidth: number;
}) => {
  const [desiredHeight, setDesiredHeight] = useState(0);

  Image.getSize(_uri, (_width, _height) => {
    setDesiredHeight((_desiredWidth / _width) * _height);
  });

  const styles = StyleSheet.create({
    image: {
      borderRadius: 4,
      width: _desiredWidth,
      height: desiredHeight,
    },
  });

  return <Image source={{ uri: _uri }} style={styles.image} />;
};

const scrollview = StyleSheet.create({
  container: { flexGrow: 1 },
});
