import React from 'react';
import { Modal, View, StyleSheet } from 'react-native';
import Gallery from 'react-native-awesome-gallery';

let controller = {
  open: (_imgs, _options) => {},
  close: () => {},
};

export const CustomImagePreview = {
  open: (imgs, options) => controller.open(imgs, options),
  close: () => controller.close(),
};

export const CustomImagePreviewHost = () => {
  const [visible, setVisible] = React.useState(false);
  const [data, setData] = React.useState([]);
  const [index, setIndex] = React.useState(0);

  React.useEffect(() => {
    controller.open = (imgs, options = {}) => {
      const arr = Array.isArray(imgs) ? imgs : [imgs];
      const urls = arr.filter((x) => typeof x === 'string' && x);
      if (!urls.length) return;
      const idxRaw = Number.isFinite(options.index) ? options.index : 0;
      const idx = Math.max(0, Math.min(urls.length - 1, Number(idxRaw) || 0));
      setData(urls);
      setIndex(idx);
      setVisible(true);
    };
    controller.close = () => setVisible(false);
  }, []);

  return (
    <Modal
      visible={visible}
      transparent
      animationType="fade"
      onRequestClose={() => setVisible(false)}
    >
      <View style={styles.overlay}>
        <Gallery
          style={{ flex: 1 }}
          data={data}
          initialIndex={index}
          onIndexChange={setIndex}
          // 点击图片关闭
          onTap={() => setVisible(false)}
          // 上下滑动关闭
          onSwipeToClose={() => setVisible(false)}
          // 默认大图：使用库默认的全屏 contain 行为
          doubleTapScale={2.5}
          maxScale={8}
          // 为避免与单击关闭冲突，禁用双击缩放
          doubleTapEnabled={false}
        />
      </View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  overlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.9)',
  },
});

export default CustomImagePreview;