import { Feather, Ionicons } from "@expo/vector-icons";
import { LinearGradient } from "expo-linear-gradient";
import { router } from "expo-router";
import { StatusBar } from "expo-status-bar";
import { useEffect, useState } from "react";
import {
  ActivityIndicator,
  Alert,
  KeyboardAvoidingView,
  Platform,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

import { useAuth } from "@/hooks/use-auth";
import { authClient } from "@/lib/auth/client";
import { storage } from "@/lib/storage";

export default function LoginScreen() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isPasswordVisible, setPasswordVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const { isAuthenticated, isLoading: authLoading } = useAuth();

  useEffect(() => {
    if (!authLoading && isAuthenticated) {
      console.log("[Login] User authenticated, redirecting to tabs...");
      router.replace("/(tabs)" as any);
    }
  }, [isAuthenticated, authLoading]);

  const handleLogin = async () => {
    console.log("[Login] handleLogin called");

    if (!email.trim() || !password.trim()) {
      console.log("[Login] Validation failed: empty email or password");
      Alert.alert("错误", "请输入邮箱和密码");
      return;
    }

    console.log("[Login] Starting login with email:", email.trim());
    setIsLoading(true);

    try {
      console.log("[Login] Calling authClient.signIn.username...");
      await new Promise<void>(async (resolve, reject) => {
        await authClient.signIn.username(
          {
            username: email.trim(),
            password,
          },
          {
            onSuccess: async (ctx) => {
              const authToken = ctx.response.headers.get("set-auth-token");
              if (authToken) {
                await storage.setItem(
                  `bestaibest.better-auth.session_token`,
                  authToken
                );
                resolve();
              } else {
                console.error("Bearer token not set");
                reject();
              }
            },
          }
        );
      });
    } catch (error: any) {
      Alert.alert("登录失败", error?.message || "邮箱或密码错误");
    } finally {
      setIsLoading(false);
      console.log("[Login] handleLogin completed");
    }
  };

  return (
    <LinearGradient colors={["#050506", "#0b0c0f"]} style={styles.gradient}>
      <SafeAreaView style={styles.safeArea}>
        <StatusBar style="light" />
        <KeyboardAvoidingView
          behavior={Platform.OS === "ios" ? "padding" : undefined}
          style={styles.flex}
        >
          <View style={styles.screen}>
            <TouchableOpacity
              activeOpacity={0.7}
              onPress={() => router.back()}
              style={styles.backButton}
            >
              <Feather name="arrow-left" size={20} color="#f2f4f8" />
            </TouchableOpacity>

            <View style={styles.sheet}>
              <View style={styles.sheetHeader}>
                <View style={styles.sheetTitleGroup}>
                  <View style={styles.iconBadge}>
                    <Ionicons name="mail-open" size={16} color="#ffffff" />
                  </View>
                  <Text style={styles.sheetTitle}>Email Login</Text>
                </View>

                <TouchableOpacity
                  activeOpacity={0.7}
                  onPress={() => router.push("/(auth)/register")}
                  disabled={isLoading}
                >
                  <Text style={[styles.registerLabel, isLoading && styles.disabledText]}>
                    Register
                  </Text>
                </TouchableOpacity>
              </View>

              <View style={styles.form}>
                <View style={styles.inputWrapper}>
                  <TextInput
                    style={styles.input}
                    placeholder="yours@example.com"
                    placeholderTextColor="#70737c"
                    value={email}
                    onChangeText={setEmail}
                    autoCapitalize="none"
                    autoCorrect={false}
                    keyboardType="email-address"
                    editable={!isLoading}
                    keyboardAppearance="dark"
                  />
                </View>

                <View style={styles.inputWrapper}>
                  <TextInput
                    style={styles.input}
                    placeholder="email password"
                    placeholderTextColor="#70737c"
                    value={password}
                    onChangeText={setPassword}
                    secureTextEntry={!isPasswordVisible}
                    autoCorrect={false}
                    editable={!isLoading}
                    keyboardAppearance="dark"
                  />
                  <TouchableOpacity
                    activeOpacity={0.7}
                    onPress={() => setPasswordVisible((visible) => !visible)}
                    style={styles.visibilityToggle}
                  >
                    <Feather
                      name={isPasswordVisible ? "eye-off" : "eye"}
                      size={18}
                      color="#8a8e97"
                    />
                  </TouchableOpacity>
                </View>

                <TouchableOpacity
                  style={[styles.loginButton, isLoading && styles.loginButtonDisabled]}
                  onPress={handleLogin}
                  disabled={isLoading}
                  activeOpacity={0.85}
                >
                  {isLoading ? (
                    <ActivityIndicator color="#0f100f" />
                  ) : (
                    <Text style={styles.loginButtonText}>Log in</Text>
                  )}
                </TouchableOpacity>

                <View style={styles.termsRow}>
                  <Ionicons name="checkmark-circle" size={16} color="#d7ff1f" />
                  <Text style={styles.termsText}>
                    已阅读并同意
                    <Text style={styles.linkText}> 用户协议 </Text>
                    和
                    <Text style={styles.linkText}> 隐私政策</Text>
                  </Text>
                </View>
              </View>
            </View>
          </View>
        </KeyboardAvoidingView>
      </SafeAreaView>
    </LinearGradient>
  );
}

const styles = StyleSheet.create({
  gradient: {
    flex: 1,
  },
  safeArea: {
    flex: 1,
  },
  flex: {
    flex: 1,
  },
  screen: {
    flex: 1,
    justifyContent: "flex-end",
    paddingHorizontal: 20,
    paddingBottom: 24,
  },
  backButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "rgba(255, 255, 255, 0.05)",
    borderWidth: 1,
    borderColor: "rgba(255, 255, 255, 0.06)",
    marginBottom: 28,
  },
  sheet: {
    backgroundColor: "#14161c",
    borderRadius: 28,
    paddingHorizontal: 24,
    paddingVertical: 28,
    borderWidth: 1,
    borderColor: "rgba(255, 255, 255, 0.08)",
    shadowColor: "#000",
    shadowOpacity: 0.25,
    shadowRadius: 18,
    shadowOffset: { width: 0, height: -8 },
    elevation: 24,
  },
  sheetHeader: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    marginBottom: 28,
  },
  sheetTitleGroup: {
    flexDirection: "row",
    alignItems: "center",
  },
  iconBadge: {
    width: 40,
    height: 40,
    borderRadius: 16,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#f6474d",
    marginRight: 12,
  },
  sheetTitle: {
    color: "#f5f6f8",
    fontSize: 22,
    fontWeight: "700",
    letterSpacing: 0.2,
  },
  registerLabel: {
    color: "#b7bac2",
    fontSize: 14,
    fontWeight: "600",
    letterSpacing: 0.3,
  },
  disabledText: {
    opacity: 0.5,
  },
  form: {
    marginTop: 4,
  },
  inputWrapper: {
    position: "relative",
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 18,
    backgroundColor: "#1a1d23",
    borderRadius: 18,
    borderWidth: 1,
    borderColor: "rgba(255, 255, 255, 0.05)",
    marginBottom: 18,
  },
  input: {
    flex: 1,
    paddingVertical: 16,
    fontSize: 16,
    color: "#f5f6f8",
    letterSpacing: 0.3,
  },
  visibilityToggle: {
    marginLeft: 12,
  },
  loginButton: {
    height: 56,
    borderRadius: 18,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#d7ff1f",
    shadowColor: "#d7ff1f",
    shadowOpacity: 0.35,
    shadowRadius: 16,
    shadowOffset: { width: 0, height: 10 },
    elevation: 10,
    marginTop: 4,
  },
  loginButtonDisabled: {
    opacity: 0.7,
  },
  loginButtonText: {
    color: "#10120d",
    fontSize: 17,
    fontWeight: "700",
    letterSpacing: 0.5,
  },
  termsRow: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    marginTop: 18,
  },
  termsText: {
    color: "#a7abb5",
    fontSize: 13,
    lineHeight: 18,
    marginLeft: 8,
  },
  linkText: {
    color: "#f5f6f8",
    fontWeight: "600",
  },
});
