import React from "react";
import {
  StyleSheet,
  Text,
  View,
  Alert,
  Platform,
  ActivityIndicator,
  TouchableOpacity,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Ionicons } from "@expo/vector-icons";
import * as AppleAuthentication from "expo-apple-authentication";
import {
  GoogleSignin,
  isSuccessResponse,
  isErrorWithCode,
  statusCodes,
} from "@react-native-google-signin/google-signin";
import { useAuth } from "../context/AuthContext";
import { GOOGLE_WEB_CLIENT_ID, GOOGLE_IOS_CLIENT_ID } from "../config";

let didConfigureGoogleSignIn = false;

type BusyProvider = "apple" | "google" | null;

// One shared button for both providers so they're guaranteed to look
// identical (same icon size, same font) instead of trying to eyeball-match
// a custom button against Apple's native one, whose font isn't
// controllable from here.
function AuthButton({
  icon,
  label,
  onPress,
  loading,
  disabled,
}: {
  icon: React.ComponentProps<typeof Ionicons>["name"];
  label: string;
  onPress: () => void;
  loading: boolean;
  disabled: boolean;
}) {
  return (
    <TouchableOpacity
      style={[styles.authBtn, disabled && styles.authBtnDisabled]}
      onPress={onPress}
      disabled={disabled}
      activeOpacity={0.8}
    >
      {loading ? (
        <ActivityIndicator color="#1F1F1F" size="small" />
      ) : (
        <>
          <Ionicons name={icon} size={18} color="#1F1F1F" />
          <Text style={styles.authBtnText}>{label}</Text>
        </>
      )}
    </TouchableOpacity>
  );
}

export default function LoginScreen() {
  const { signInWithGoogleIdToken, signInWithAppleIdentityToken } = useAuth();
  const [busyProvider, setBusyProvider] = React.useState<BusyProvider>(null);
  const [appleAvailable, setAppleAvailable] = React.useState(false);

  React.useEffect(() => {
    if (Platform.OS !== "ios") return;
    AppleAuthentication.isAvailableAsync()
      .then(setAppleAvailable)
      .catch(() => setAppleAvailable(false));
  }, []);

  React.useEffect(() => {
    if (didConfigureGoogleSignIn || !GOOGLE_WEB_CLIENT_ID) return;
    GoogleSignin.configure({
      webClientId: GOOGLE_WEB_CLIENT_ID,
      iosClientId: GOOGLE_IOS_CLIENT_ID || undefined,
    });
    didConfigureGoogleSignIn = true;
  }, []);

  const handleGooglePress = async () => {
    if (!GOOGLE_WEB_CLIENT_ID) {
      Alert.alert(
        "Not configured yet",
        "Google sign-in needs EXPO_PUBLIC_GOOGLE_WEB_CLIENT_ID set and a native rebuild.",
      );
      return;
    }
    try {
      setBusyProvider("google");
      await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
      const response = await GoogleSignin.signIn();
      if (!isSuccessResponse(response)) return; // user cancelled
      const { idToken } = response.data;
      if (!idToken) throw new Error("Google did not return an ID token.");
      await signInWithGoogleIdToken(idToken);
    } catch (err: any) {
      if (isErrorWithCode(err) && err.code === statusCodes.SIGN_IN_CANCELLED) {
        // no-op: user cancelled
      } else {
        Alert.alert("Google sign-in failed", err.message || String(err));
      }
    } finally {
      setBusyProvider(null);
    }
  };

  const handleApplePress = async () => {
    try {
      setBusyProvider("apple");
      const credential = await AppleAuthentication.signInAsync({
        requestedScopes: [
          AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
          AppleAuthentication.AppleAuthenticationScope.EMAIL,
        ],
      });
      if (!credential.identityToken) {
        throw new Error("Apple did not return an identity token.");
      }
      const fullName = credential.fullName
        ? AppleAuthentication.formatFullName(credential.fullName)
        : undefined;
      await signInWithAppleIdentityToken(credential.identityToken, fullName);
    } catch (err: any) {
      if (err.code !== "ERR_REQUEST_CANCELED") {
        Alert.alert("Apple sign-in failed", err.message || String(err));
      }
    } finally {
      setBusyProvider(null);
    }
  };

  const disabled = busyProvider !== null;

  return (
    <SafeAreaView style={styles.container} edges={["top", "bottom"]}>
      <View style={styles.content}>
        <View style={styles.logoWrap}>
          <Ionicons name="musical-notes" size={56} color="#1DB954" />
        </View>
        <Text style={styles.title}>Welcome</Text>
        <Text style={styles.subtitle}>
          Sign in to continue — your downloads and playlists stay fully on
          this device either way.
        </Text>

        <View style={styles.buttons}>
          {appleAvailable && (
            <AuthButton
              icon="logo-apple"
              label="Sign in with Apple"
              onPress={handleApplePress}
              loading={busyProvider === "apple"}
              disabled={disabled}
            />
          )}
          {Platform.OS === "ios" && !appleAvailable && (
            <Text style={styles.hint}>
              Sign in with Apple needs a custom dev build, not Expo Go.
            </Text>
          )}

          <AuthButton
            icon="logo-google"
            label="Sign in with Google"
            onPress={handleGooglePress}
            loading={busyProvider === "google"}
            disabled={disabled}
          />
          {!GOOGLE_WEB_CLIENT_ID && (
            <Text style={styles.hint}>
              Google sign-in isn&apos;t configured yet.
            </Text>
          )}
        </View>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#121212" },
  content: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    paddingHorizontal: 32,
  },
  logoWrap: {
    width: 96,
    height: 96,
    borderRadius: 48,
    backgroundColor: "#1E1E1E",
    alignItems: "center",
    justifyContent: "center",
    marginBottom: 24,
  },
  title: { color: "#FFF", fontSize: 26, fontWeight: "bold" },
  subtitle: {
    color: "#888",
    fontSize: 14,
    textAlign: "center",
    marginTop: 10,
    marginBottom: 40,
    lineHeight: 20,
  },
  buttons: { width: "100%", alignItems: "center" },
  authBtn: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#FFF",
    width: "100%",
    height: 46,
    borderRadius: 8,
    marginBottom: 14,
  },
  authBtnDisabled: { opacity: 0.6 },
  authBtnText: {
    color: "#1F1F1F",
    fontWeight: "600",
    fontSize: 16,
    marginLeft: 10,
  },
  hint: {
    color: "#666",
    fontSize: 12,
    marginTop: -6,
    marginBottom: 6,
    textAlign: "center",
  },
});
