import { ThemedText } from "@/components/themed-text";
import { ThemedView } from "@/components/themed-view";
import { storage } from "@/lib/storage";
import { useEffect, useState } from "react";
import { Alert, StyleSheet, TouchableOpacity, View } from "react-native";

export function DebugSession() {
  const [sessionToken, setSessionToken] = useState<string | null>(null);

  const loadSessionToken = async () => {
    try {
      const token = storage.getItem("bestaibest.better-auth.session_token");
      setSessionToken(token);
    } catch (error) {
      console.error("Error loading session token:", error);
    }
  };

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

  const handleRefresh = () => {
    loadSessionToken();
  };

  const handleClear = async () => {
    Alert.alert("清除会话", "确定要清除 SecureStore 中的会话数据吗？", [
      { text: "取消", style: "cancel" },
      {
        text: "确定",
        style: "destructive",
        onPress: async () => {
          console.log("[DebugSession] Clearing session token...");
          storage.removeItem("bestaibest.better-auth.session_token");
          
          setTimeout(() => {
            console.log("[DebugSession] Reloading token to verify...");
            loadSessionToken();
          }, 100);
          
          Alert.alert("成功", "会话已清除");
        },
      },
    ]);
  };

  return (
    <ThemedView style={styles.container}>
      <ThemedText type="subtitle" style={styles.title}>
        调试信息
      </ThemedText>

      <View style={styles.infoRow}>
        <ThemedText style={styles.label}>Session Token:</ThemedText>
        <ThemedText style={styles.value} numberOfLines={1}>
          {sessionToken ? `${sessionToken.slice(0, 20)}...` : "无"}
        </ThemedText>
      </View>

      <View style={styles.actions}>
        <TouchableOpacity style={styles.button} onPress={handleRefresh}>
          <ThemedText style={styles.buttonText}>刷新</ThemedText>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.button, styles.dangerButton]}
          onPress={handleClear}
        >
          <ThemedText style={styles.buttonText}>清除会话</ThemedText>
        </TouchableOpacity>
      </View>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 16,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: "#ddd",
    marginVertical: 16,
  },
  title: {
    marginBottom: 12,
  },
  infoRow: {
    marginBottom: 8,
  },
  label: {
    fontWeight: "600",
    marginBottom: 4,
  },
  value: {
    fontFamily: "monospace",
    fontSize: 12,
    opacity: 0.7,
  },
  actions: {
    flexDirection: "row",
    gap: 8,
    marginTop: 12,
  },
  button: {
    flex: 1,
    backgroundColor: "#007AFF",
    padding: 12,
    borderRadius: 6,
    alignItems: "center",
  },
  dangerButton: {
    backgroundColor: "#FF3B30",
  },
  buttonText: {
    color: "#fff",
    fontWeight: "600",
    fontSize: 14,
  },
});
