import AsyncStorage from "@react-native-async-storage/async-storage";
import { usePathname, useRouter } from "expo-router";
import React, { useEffect, useState } from "react";
import {
    BackHandler,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
} from "react-native";

export function PrivacyPopup() {
  const [agreed, setAgreed] = useState<boolean | null>(null);
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    checkPrivacyStatus();
  }, []);

  const checkPrivacyStatus = async () => {
    try {
      const status = await AsyncStorage.getItem("hasAgreedPrivacy");
      setAgreed(status === "true");
    } catch (e) {
      setAgreed(false);
    }
  };

  const handleAgree = async () => {
    try {
      await AsyncStorage.setItem("hasAgreedPrivacy", "true");
      setAgreed(true);
    } catch (e) {
      console.warn("Failed to save privacy status");
    }
  };

  const handleDisagree = () => {
    if (Platform.OS === "android") {
      BackHandler.exitApp();
    }
  };

  const openUserAgreement = () => {
    router.push({ pathname: "/agreement", params: { type: "user.html" } });
  };

  const openPrivacyPolicy = () => {
    router.push({ pathname: "/agreement", params: { type: "privacy.html" } });
  };

  if (agreed === null || agreed === true) {
    return null;
  }

  // 隐藏弹窗以允许查看协议
  if (pathname === "/agreement") {
    return null;
  }

  return (
    <View style={styles.overlay}>
      <View style={styles.container}>
        <Text style={styles.title}>个人信息保护指引</Text>
        <ScrollView style={styles.scroll}>
          <Text style={styles.content}>
            感谢您使用我们要提供给您的服务！我们非常重视您的个人信息和隐私保护。在您使用我们的服务之前，请务必仔细阅读
            <Text style={styles.link} onPress={openUserAgreement}>
              《用户协议》
            </Text>
            和
            <Text style={styles.link} onPress={openPrivacyPolicy}>
              《隐私政策》
            </Text>
            。{"\n\n"}
            我们将严格按照上述协议/政策为您提供服务，保护您的个人信息安全。如果您同意以上内容，请点击“同意”开始使用。
          </Text>
        </ScrollView>
        <View style={styles.btnRow}>
          <TouchableOpacity
            style={styles.disagreeBtn}
            onPress={handleDisagree}
            activeOpacity={0.8}
          >
            <Text style={styles.disagreeText}>不同意并退出</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.agreeBtn}
            onPress={handleAgree}
            activeOpacity={0.8}
          >
            <Text style={styles.agreeText}>同意</Text>
          </TouchableOpacity>
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  overlay: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: "rgba(0,0,0,0.6)",
    justifyContent: "center",
    alignItems: "center",
    padding: 30,
    zIndex: 9999,
    elevation: 9999,
  },
  container: {
    width: "100%",
    backgroundColor: "#fff",
    borderRadius: 12,
    padding: 24,
    maxHeight: "70%",
  },
  title: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#333",
    textAlign: "center",
    marginBottom: 15,
  },
  scroll: {
    maxHeight: 250,
  },
  content: {
    fontSize: 14,
    color: "#666",
    lineHeight: 22,
  },
  link: {
    color: "#8b3dff",
  },
  btnRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginTop: 20,
  },
  disagreeBtn: {
    flex: 1,
    paddingVertical: 12,
    alignItems: "center",
    backgroundColor: "#f5f5f5",
    borderRadius: 20,
    marginRight: 10,
  },
  disagreeText: {
    color: "#999",
    fontSize: 14,
  },
  agreeBtn: {
    flex: 1,
    paddingVertical: 12,
    alignItems: "center",
    backgroundColor: "#8b3dff",
    borderRadius: 20,
    marginLeft: 10,
  },
  agreeText: {
    color: "#fff",
    fontSize: 14,
    fontWeight: "bold",
  },
});
