import React, { useState, useEffect } from "react";
import { Alert } from "react-native";
import { WebView } from "react-native-webview";
import { get } from "../../utils/storeInfo";
import * as FileSystem from "expo-file-system";
import * as MediaLibrary from "expo-media-library";
import * as Linking from "expo-linking";
import * as Clipboard from "expo-clipboard";
import Toast from "react-native-toast-message";
import MyModal from "../../components/MyModal";
import baseRequest from "../../utils/baseRequest";

export default function WebWithHeader({ navigation, route }) {
  //设置页面标题
  useEffect(() => {
    navigation.setOptions({
      title: route.params?.title,
    });
  }, [navigation, route]);

  //前往打开权限弹窗
  const [overlayVisible, setOverlayVisible] = useState(false);

  //设置cookies
  const [cookies, setCookies] = useState();
  useEffect(() => {
    async function getCookies() {
      const token = await get("token");
      const account = await get("account");
      const base = await baseRequest();
      setCookies({ token: token, account: account, base: base });
    }
    getCookies();
  }, []);

  const setCookieScript = `
  document.cookie = "token=${cookies?.token} ;";
  document.cookie = "account=${cookies?.account} ;";
  document.cookie = "base=${cookies?.base} ;";
  true;
`;

  //请求相册访问权限并保存
  const saveImage = async (data) => {
    const permission = await MediaLibrary.requestPermissionsAsync();
    if (permission.granted) {
      const base64Code = data.split("data:image/png;base64,")[1];
      const filename = FileSystem.cacheDirectory + "poster.png";

      await FileSystem.writeAsStringAsync(filename, base64Code, {
        encoding: FileSystem.EncodingType.Base64,
      });

      await MediaLibrary.saveToLibraryAsync(filename);

      Toast.show({
        type: "success",
        text1: "已保存到相册",
        topOffset: 60,
      });
    } else {
      setOverlayVisible(true);
    }
  };

  //保存内容到剪贴板
  const copy = async (data) => {
    await Clipboard.setStringAsync(data);
    Toast.show({
      type: "success",
      text1: "已复制到剪贴板",
      topOffset: 60,
    });
  };

  //唤起支付宝
  const handleUrlRedirect = (event) => {
    const { url } = event;

    // 对alipays:相关的scheme处理
    if (url.startsWith("alipays:") || url.startsWith("alipay")) {
      try {
        // 尝试启动支付宝客户端
        Linking.openURL(url).catch(() => {
          // 启动支付宝客户端失败，弹出提示安装对话框
          Alert.alert(
            "支付宝提醒",
            "未检测到支付宝客户端，请安装后重试。",
            [
              {
                text: "立即安装",
                onPress: () => {
                  const alipayUrl = "https://d.alipay.com";
                  Linking.openURL(alipayUrl);
                },
              },
              { text: "取消", style: "cancel" },
            ],
            { cancelable: false }
          );
        });
        return true; // 应用程序处理了该URL
      } catch (error) {
        // 启动支付宝客户端失败，继续加载URL
        console.error(error);
      }
    }

    // weixin:相关的scheme处理
    if (url.startsWith("weixin:")) {
      try {
        // 尝试启动支付宝客户端
        Linking.openURL(url).catch(() => {
          // 启动微信客户端失败，弹出提示安装对话框
          Alert.alert(
            "微信提醒",
            "未检测到微信客户端，请安装后重试。",
            [{ text: "确认", style: "cancel" }],
            { cancelable: false }
          );
        });
        return true; // 应用程序处理了该URL
      } catch (error) {
        // 启动微信客户端失败，继续加载URL
        console.error(error);
      }
    }

    // 处理其他URL
    return true;
  };

  return (
    <>
      <WebView
        source={{
          uri: route.params.uri,
        }}
        userAgent="FromWebview"
        onMessage={async (event) => {
          const msg = JSON.parse(event.nativeEvent.data);
          if (msg.type === "SAVE_IMAGE") {
            saveImage(msg.data);
          } else if (msg.type === "COPY_URL") {
            copy(msg.data);
          } else if (msg.type === "NAVIGATE") {
            navigation.navigate(msg.data.page, { ...msg.data.params });
          }
        }}
        injectedJavaScript={setCookieScript}
        originWhitelist={[
          "https://*",
          "http://*",
          "alipays://*",
          "alipay://*",
          "weixin://*",
        ]}
        onShouldStartLoadWithRequest={handleUrlRedirect}
      />
      <MyModal
        visible={overlayVisible}
        setVisible={setOverlayVisible}
        title="您还未打开媒体权限"
        content="是否前往设置开启权限？"
        cancel={() => {
          setOverlayVisible(false);
        }}
        confirm={() => {
          Linking.openSettings();
          setOverlayVisible(false);
        }}
      />
    </>
  );
}
