import {RouteProp} from '@react-navigation/core';
import {StackNavigationProp} from '@react-navigation/stack';
import {default as React, useEffect, useState} from 'react';
import {Image, StyleSheet, TouchableOpacity} from 'react-native';
import {normalize} from 'react-native-elements';
import ImageZoom, {IOnMove} from 'react-native-image-pan-zoom';
import PhotoManipulator from 'react-native-photo-manipulator';
import CloseIcon from '../../assets/ionicons/close-outline.svg';
import {MainStackParams} from '../../routes';
import {HeaderHeight, SCREEN_HEIGHT, SCREEN_WIDTH} from '../../utils';
import {TaggSquareButton} from '../common';

type ZoomInCropperRouteProps = RouteProp<MainStackParams, 'ZoomInCropper'>;
type ZoomInCropperNavigationProps = StackNavigationProp<
  MainStackParams,
  'ZoomInCropper'
>;
interface ZoomInCropperProps {
  route: ZoomInCropperRouteProps;
  navigation: ZoomInCropperNavigationProps;
}

export const ZoomInCropper: React.FC<ZoomInCropperProps> = ({
  route,
  navigation,
}) => {
  const {screenType, title, image} = route.params;
  const [aspectRatio, setAspectRatio] = useState<number>(1);

  useEffect(() => {
    navigation.dangerouslyGetParent()?.setOptions({
      tabBarVisible: false,
    });
  }, []);

  useEffect(() => {
    if (image.sourceURL) {
      Image.getSize(
        image.sourceURL,
        (w, h) => {
          setAspectRatio(w / h);
        },
        (err) => console.log(err),
      );
    }
  }, []);

  const handleNext = () => {
    console.log('x0: ', x0, 'x1: ', x1, 'y0: ', y0, 'y1: ', y1);
    if (
      x0 !== undefined &&
      x1 !== undefined &&
      y0 !== undefined &&
      y1 !== undefined &&
      image.sourceURL
    ) {
      console.log('x0x1y0y1');
      PhotoManipulator.crop(image.sourceURL, {
        x: x0,
        y: y1,
        width: Math.abs(x0 - x1),
        height: Math.abs(y0 - y1),
      })
        .then((croppedURL) => {
          navigation.navigate('CaptionScreen', {
            screenType,
            title: title,
            image: {filename: croppedURL, path: croppedURL},
          });
        })
        .catch((err) => console.log('err: ', err));
    } else if (
      x0 === undefined &&
      x1 === undefined &&
      y0 === undefined &&
      y1 === undefined &&
      image.sourceURL
    ) {
      navigation.navigate('CaptionScreen', {
        screenType,
        title: title,
        image: {filename: image.sourceURL, path: image.sourceURL},
      });
    }
    console.log('crop photo and send to caption screen');
  };

  const [x0, setX0] = useState<number>();
  const [x1, setX1] = useState<number>();
  const [y0, setY0] = useState<number>();
  const [y1, setY1] = useState<number>();

  const onMove = (position: IOnMove) => {
    Image.getSize(
      image.path,
      (w, h) => {
        const x = position.positionX;
        const y = position.positionY;
        const scale = position.scale;
        const screen_ratio = SCREEN_HEIGHT / SCREEN_WIDTH;
        let x0 = w / 2 - x * (w / SCREEN_WIDTH) - w / 2 / scale;
        let x1 = w / 2 - x * (w / SCREEN_WIDTH) + w / 2 / scale;
        if (x0 < 0) {
          x0 = 0;
        }
        if (x1 > w) {
          x1 = w;
        }
        const x_distance = Math.abs(x1 - x0);
        const y_distance = screen_ratio * x_distance;
        let y0 = h / 2 - y * (h / SCREEN_HEIGHT) + y_distance / 2;
        let y1 = h / 2 - y * (h / SCREEN_HEIGHT) - y_distance / 2;
        if (y0 > h) {
          y0 = h;
        }
        if (y1 < 0) {
          y1 = 0;
        }
        console.log('onMove x0: ', x0, 'x1: ', x1, 'y0: ', y0, 'y1: ', y1);
        setX0(x0);
        setX1(x1);
        setY0(y0);
        setY1(y1);
      },
      (err) => console.log(err),
    );
  };

  return (
    <>
      <TouchableOpacity
        style={styles.closeButton}
        onPress={() => navigation.goBack()}>
        <CloseIcon height={25} width={25} color={'white'} />
      </TouchableOpacity>
      <ImageZoom
        style={{backgroundColor: 'black'}}
        cropWidth={SCREEN_WIDTH}
        cropHeight={SCREEN_HEIGHT}
        imageWidth={SCREEN_WIDTH}
        imageHeight={SCREEN_WIDTH / aspectRatio}
        onMove={onMove}>
        <Image
          style={{width: SCREEN_WIDTH, height: SCREEN_WIDTH / aspectRatio}}
          source={{
            uri: image.sourceURL,
          }}
        />
      </ImageZoom>
      <TaggSquareButton
        onPress={handleNext}
        title={'Next'}
        buttonStyle={'normal'}
        buttonColor={'blue'}
        labelColor={'white'}
        style={styles.button}
        labelStyle={styles.buttonLabel}
      />
    </>
  );
};

const styles = StyleSheet.create({
  closeButton: {
    position: 'absolute',
    top: 0,
    paddingTop: HeaderHeight,
    zIndex: 1,
    marginLeft: '5%',
  },
  button: {
    zIndex: 1,
    position: 'absolute',
    bottom: normalize(20),
    right: normalize(15),
    width: normalize(108),
    height: normalize(25),
    borderRadius: 10,
  },
  buttonLabel: {
    fontWeight: '700',
    fontSize: normalize(15),
    lineHeight: normalize(17.8),
    letterSpacing: normalize(1.3),
    textAlign: 'center',
  },
});
