import { useState } from "react";
import {
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableOpacity,
  ScrollView,
  Platform,
  ActivityIndicator,
  Image,
  Alert,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useRouter } from "expo-router";
import { LogIn, UserPlus } from "lucide-react-native";
import Colors from "@/constants/colors";
import { useAuth } from "@/lib/auth-context";

export default function AuthScreen() {
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const { login, register, verifyTwoFactorLogin, isLoading: authLoading } = useAuth();

  const [mode, setMode] = useState<"login" | "register">("login");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string>("");
  const [mfaStep, setMfaStep] = useState(false);
  const [mfaChallengeId, setMfaChallengeId] = useState<string | null>(null);
  const [totpCode, setTotpCode] = useState("");

  const [identifier, setIdentifier] = useState("");
  const [password, setPassword] = useState("");
  const [displayName, setDisplayName] = useState("");
  const [email, setEmail] = useState("");
  const [phoneNumber, setPhoneNumber] = useState("");

  const handleLogin = async () => {
    if (!identifier || !password) {
      setError("Please fill in all fields");
      return;
    }

    setIsLoading(true);
    setError("");

    const result = await login(identifier.trim(), password);
    setIsLoading(false);

    if (result.success && result.requires2FA && result.challengeId) {
      setMfaChallengeId(result.challengeId);
      setMfaStep(true);
      return;
    }

    if (result.success) {
      router.replace("/(tabs)");
    } else {
      setError(result.error || "Login failed");
    }
  };

  const handleVerifyMfa = async () => {
    if (!mfaChallengeId || totpCode.length < 6) {
      setError("Enter your 6-digit authenticator code");
      return;
    }
    setIsLoading(true);
    setError("");
    const result = await verifyTwoFactorLogin(mfaChallengeId, totpCode);
    setIsLoading(false);
    if (result.success) {
      router.replace("/(tabs)");
    } else {
      setError(result.error || "Invalid code");
    }
  };

  const handleRegister = async () => {
    if (!displayName) {
      setError("Please enter your name");
      return;
    }

    if (!email && !phoneNumber) {
      setError("Enter an email address or phone number");
      return;
    }

    if (!password) {
      setError("Please choose a password");
      return;
    }

    if (password.length < 8) {
      setError("Password must be at least 8 characters");
      return;
    }

    setIsLoading(true);
    setError("");

    const result = await register({
      email: email ? email.trim().toLowerCase() : undefined,
      phoneNumber: phoneNumber ? phoneNumber.trim() : undefined,
      password,
      displayName: displayName.trim(),
    });

    setIsLoading(false);

    if (result.success) {
      if (result.username) {
        Alert.alert("Welcome to Zendo", `Your handle is @${result.username}. You can change it anytime from your profile.`, [
          { text: "Get Started", onPress: () => router.replace("/(tabs)") },
        ]);
      } else {
        router.replace("/(tabs)");
      }
    } else {
      setError(result.error || "Registration failed");
    }
  };

  if (authLoading) {
    return (
      <View style={[styles.container, { paddingTop: insets.top }]}>
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={Colors.dark.primary} />
          <Text style={styles.loadingText}>Loading...</Text>
        </View>
      </View>
    );
  }

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={styles.scrollContent}
        keyboardShouldPersistTaps="handled"
      >
        <View style={styles.headerContainer}>
          <Image
            source={require("../assets/images/zendo-logo.png")}
            style={styles.logo}
            resizeMode="contain"
          />
          <Text style={styles.tagline}>Sovereign-grade payment platform</Text>
        </View>

        <View style={styles.formCard}>
          <View style={styles.modeSelector}>
            <TouchableOpacity
              style={[styles.modeButton, mode === "login" && styles.modeButtonActive]}
              onPress={() => {
                setMode("login");
                setError("");
              }}
            >
              <LogIn
                size={18}
                color={mode === "login" ? Colors.dark.background : Colors.dark.textSecondary}
              />
              <Text
                style={[
                  styles.modeButtonText,
                  mode === "login" && styles.modeButtonTextActive,
                ]}
              >
                Login
              </Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.modeButton, mode === "register" && styles.modeButtonActive]}
              onPress={() => {
                setMode("register");
                setError("");
              }}
            >
              <UserPlus
                size={18}
                color={mode === "register" ? Colors.dark.background : Colors.dark.textSecondary}
              />
              <Text
                style={[
                  styles.modeButtonText,
                  mode === "register" && styles.modeButtonTextActive,
                ]}
              >
                Register
              </Text>
            </TouchableOpacity>
          </View>

          {error ? <Text style={styles.errorText}>{error}</Text> : null}

          {mfaStep ? (
            <>
              <Text style={styles.mfaTitle}>Two-factor authentication</Text>
              <Text style={styles.mfaSub}>Enter the 6-digit code from your authenticator app.</Text>
              <View style={styles.inputContainer}>
                <TextInput
                  style={[styles.input, styles.mfaInput]}
                  value={totpCode}
                  onChangeText={setTotpCode}
                  placeholder="000000"
                  placeholderTextColor={Colors.dark.textTertiary}
                  keyboardType="number-pad"
                  maxLength={9}
                  autoFocus
                />
              </View>
              <TouchableOpacity
                style={[styles.submitButton, isLoading && styles.submitButtonDisabled]}
                onPress={handleVerifyMfa}
                disabled={isLoading}
              >
                {isLoading ? (
                  <ActivityIndicator size="small" color={Colors.dark.background} />
                ) : (
                  <Text style={styles.submitButtonText}>Verify & Sign In</Text>
                )}
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.forgotPasswordLink}
                onPress={() => {
                  setMfaStep(false);
                  setMfaChallengeId(null);
                  setTotpCode("");
                  setError("");
                }}
              >
                <Text style={styles.forgotPasswordText}>Back to login</Text>
              </TouchableOpacity>
            </>
          ) : (
            <>
          {mode === "register" && (
            <View style={styles.inputContainer}>
              <Text style={styles.inputLabel}>Full Name *</Text>
              <TextInput
                style={styles.input}
                value={displayName}
                onChangeText={setDisplayName}
                placeholder="John Doe"
                placeholderTextColor={Colors.dark.textTertiary}
                autoCapitalize="words"
              />
            </View>
          )}

          {mode === "login" ? (
            <View style={styles.inputContainer}>
              <Text style={styles.inputLabel}>Email or Phone Number</Text>
              <TextInput
                style={styles.input}
                value={identifier}
                onChangeText={setIdentifier}
                placeholder="your@email.com or phone number"
                placeholderTextColor={Colors.dark.textTertiary}
                autoCapitalize="none"
              />
            </View>
          ) : (
            <>
              <View style={styles.inputContainer}>
                <Text style={styles.inputLabel}>Email</Text>
                <TextInput
                  style={styles.input}
                  value={email}
                  onChangeText={setEmail}
                  placeholder="your@email.com"
                  placeholderTextColor={Colors.dark.textTertiary}
                  keyboardType="email-address"
                  autoCapitalize="none"
                />
              </View>

              <View style={styles.inputContainer}>
                <Text style={styles.inputLabel}>Phone Number</Text>
                <TextInput
                  style={styles.input}
                  value={phoneNumber}
                  onChangeText={setPhoneNumber}
                  placeholder="+1 (555) 123-4567"
                  placeholderTextColor={Colors.dark.textTertiary}
                  keyboardType="phone-pad"
                />
                <Text style={styles.inputHint}>Add at least an email or a phone number</Text>
              </View>
            </>
          )}

          <View style={styles.inputContainer}>
            <Text style={styles.inputLabel}>Password *</Text>
            <TextInput
              style={styles.input}
              value={password}
              onChangeText={setPassword}
              placeholder="••••••••"
              placeholderTextColor={Colors.dark.textTertiary}
              secureTextEntry
              autoCapitalize="none"
            />
          </View>

          {mode === "register" && (
            <Text style={styles.handleNotice}>
              We&apos;ll create a unique @handle for you - you can change it anytime from your profile.
            </Text>
          )}

          <TouchableOpacity
            style={[styles.submitButton, isLoading && styles.submitButtonDisabled]}
            onPress={mode === "login" ? handleLogin : handleRegister}
            disabled={isLoading}
          >
            {isLoading ? (
              <ActivityIndicator size="small" color={Colors.dark.background} />
            ) : (
              <Text style={styles.submitButtonText}>
                {mode === "login" ? "Login" : "Create Account"}
              </Text>
            )}
          </TouchableOpacity>

          {mode === "login" && (
            <TouchableOpacity
              style={styles.forgotPasswordLink}
              onPress={() => router.push("/forgot-password")}
            >
              <Text style={styles.forgotPasswordText}>Forgot password?</Text>
            </TouchableOpacity>
          )}
            </>
          )}
        </View>

        <View style={styles.footer}>
          <Text style={styles.footerText}>
            By continuing, you agree to our Terms of Service and Privacy Policy
          </Text>
        </View>
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.dark.background,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    padding: 20,
    paddingBottom: 60,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    gap: 16,
  },
  loadingText: {
    fontSize: 16,
    color: Colors.dark.textSecondary,
  },
  headerContainer: {
    alignItems: "center",
    marginTop: 40,
    marginBottom: 40,
  },
  logo: {
    width: 200,
    height: 60,
    marginBottom: 8,
  },
  tagline: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
    textAlign: "center",
  },
  formCard: {
    backgroundColor: Colors.dark.surface,
    borderRadius: 20,
    padding: 24,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    gap: 20,
  },
  modeSelector: {
    flexDirection: "row",
    gap: 12,
    marginBottom: 8,
  },
  modeButton: {
    flex: 1,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderRadius: 12,
    backgroundColor: Colors.dark.surfaceElevated,
    gap: 8,
  },
  modeButtonActive: {
    backgroundColor: Colors.dark.primary,
  },
  modeButtonText: {
    fontSize: 15,
    fontWeight: "600" as const,
    color: Colors.dark.textSecondary,
  },
  modeButtonTextActive: {
    color: Colors.dark.background,
  },
  errorText: {
    fontSize: 14,
    color: Colors.dark.error,
    textAlign: "center",
    paddingHorizontal: 12,
    paddingVertical: 8,
    backgroundColor: `${Colors.dark.error}20`,
    borderRadius: 8,
  },
  inputContainer: {
    gap: 8,
  },
  inputLabel: {
    fontSize: 13,
    fontWeight: "600" as const,
    color: Colors.dark.textSecondary,
    textTransform: "uppercase",
    letterSpacing: 0.5,
  },
  input: {
    fontSize: 16,
    color: Colors.dark.text,
    backgroundColor: Colors.dark.surfaceElevated,
    paddingHorizontal: 16,
    paddingVertical: 14,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    ...Platform.select({
      web: {
        outlineStyle: "none",
      },
    }),
  },
  submitButton: {
    backgroundColor: Colors.dark.primary,
    paddingVertical: 16,
    borderRadius: 12,
    alignItems: "center",
    marginTop: 8,
  },
  submitButtonDisabled: {
    opacity: 0.6,
  },
  submitButtonText: {
    fontSize: 16,
    fontWeight: "700" as const,
    color: Colors.dark.background,
  },
  footer: {
    marginTop: 24,
    paddingHorizontal: 20,
  },
  footerText: {
    fontSize: 12,
    color: Colors.dark.textTertiary,
    textAlign: "center",
    lineHeight: 18,
  },
  inputHint: {
    fontSize: 12,
    color: Colors.dark.textTertiary,
    marginTop: -4,
  },
  handleNotice: {
    fontSize: 12,
    color: Colors.dark.textTertiary,
    textAlign: "center" as const,
    lineHeight: 16,
  },
  forgotPasswordLink: {
    alignItems: "center" as const,
    paddingVertical: 8,
  },
  forgotPasswordText: {
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.textSecondary,
  },
  mfaTitle: {
    fontSize: 18,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    marginBottom: 8,
    textAlign: "center" as const,
  },
  mfaSub: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
    textAlign: "center" as const,
    marginBottom: 16,
    lineHeight: 20,
  },
  mfaInput: {
    textAlign: "center" as const,
    fontSize: 22,
    fontWeight: "700" as const,
    letterSpacing: 6,
  },
});
