import { Image } from "expo-image";
import React, { forwardRef, useImperativeHandle, useState } from "react";
import { Modal, StyleSheet, Text, TouchableOpacity, View } from "react-native";

export interface KefuPopupRef {
  open: () => void;
  close: () => void;
}

interface KefuPopupProps {
  onClose?: () => void;
}

export const KefuPopup = forwardRef<KefuPopupRef, KefuPopupProps>(
  ({ onClose }, ref) => {
    const [visible, setVisible] = useState(false);

    useImperativeHandle(ref, () => ({
      open: () => setVisible(true),
      close: () => {
        setVisible(false);
        onClose?.();
      },
    }));

    const handleClose = () => {
      setVisible(false);
      onClose?.();
    };

    return (
      <Modal
        visible={visible}
        transparent
        animationType="fade"
        onRequestClose={handleClose}
      >
        <View style={styles.overlay}>
          <TouchableOpacity
            style={styles.backdrop}
            activeOpacity={1}
            onPress={handleClose}
          />
          <View style={styles.content}>
            <Image
              source={{ uri: "https://cdn.acefig.com/kefu/qr.jpg" }}
              style={styles.qrImage}
              contentFit="contain"
            />
            <Text style={styles.tipText}>长按识别二维码添加客服</Text>
            <TouchableOpacity style={styles.closeBtn} onPress={handleClose}>
              <Text style={styles.closeBtnText}>关闭</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    );
  },
);

const styles = StyleSheet.create({
  overlay: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  backdrop: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: "rgba(0, 0, 0, 0.5)",
  },
  content: {
    backgroundColor: "#fff",
    borderRadius: 15,
    padding: 20,
    alignItems: "center",
    zIndex: 10,
  },
  qrImage: {
    width: 250,
    height: 250,
  },
  tipText: {
    fontSize: 14,
    color: "#666",
    marginTop: 15,
    marginBottom: 20,
  },
  closeBtn: {
    backgroundColor: "#FC7D2E",
    paddingHorizontal: 40,
    paddingVertical: 12,
    borderRadius: 25,
  },
  closeBtnText: {
    color: "#fff",
    fontSize: 16,
    fontWeight: "bold",
  },
});
