import React from "react";
import {
  StyleSheet,
  Text,
  View,
  Switch,
  TouchableOpacity,
  Alert,
  Image,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { router, useFocusEffect } from "expo-router";
import { Ionicons } from "@expo/vector-icons";
import { useMedia } from "../context/MediaContext";
import { useAuth } from "../context/AuthContext";
import { useEntitlement } from "../context/EntitlementContext";
import { useMiniPlayerInset } from "../hooks/useMiniPlayerInset";

function DownloadEntitlementSection() {
  const { config, refreshEntitlement, openBuyModal } = useEntitlement();

  // Re-fetch every time this screen comes into focus (not just on first
  // mount) so the count is never stale after downloads/purchases happened
  // elsewhere in the app.
  useFocusEffect(
    React.useCallback(() => {
      refreshEntitlement();
    }, [refreshEntitlement]),
  );

  // Paywall off, or the fetch hasn't resolved yet — nothing worth showing.
  // This is the ONLY place the paywall surfaces in Settings — when it's
  // off, the user never sees any hint that a payment feature exists.
  if (!config || !config.paywallEnabled) return null;

  return (
    <View style={styles.entitlementRow}>
      <Ionicons name="cloud-download-outline" size={20} color="#1DB954" />
      <View style={{ flex: 1, marginLeft: 12 }}>
        <Text style={styles.settingText}>
          {config.freeDownloadsRemaining > 0
            ? `${config.freeDownloadsRemaining} free download${config.freeDownloadsRemaining === 1 ? "" : "s"} left`
            : "Free downloads used up"}
        </Text>
        {config.purchasedCredits > 0 && (
          <Text style={styles.profileSub}>
            {config.purchasedCredits} purchased credit{config.purchasedCredits === 1 ? "" : "s"}
          </Text>
        )}
      </View>
      <TouchableOpacity style={styles.buyBtn} onPress={openBuyModal}>
        <Text style={styles.buyBtnText}>Buy more credits</Text>
      </TouchableOpacity>
    </View>
  );
}

function AccountSection() {
  const { user, signOut } = useAuth();

  const handleSignOut = () => {
    Alert.alert(
      "Sign Out",
      // Sign-in here is identity + entitlement tracking only, not a sync
      // boundary — signing out never touches local storage. Said
      // explicitly so it's never a surprise (note: this is specifically
      // about downloads/playlists, which are device-local and unscoped
      // per-account — unlike History, which is server-side and correctly
      // follows whichever account is signed in).
      "Your downloaded media and playlists are stored on this device and won't be deleted by signing out. If you want to discard them, sign back in and use \"Clear Local Download Cache\" in Settings.",
      [
        { text: "Cancel", style: "cancel" },
        { text: "Sign Out", style: "destructive", onPress: () => signOut() },
      ],
    );
  };

  // This screen is only reachable while signed in (see the Stack.Protected
  // guard in _layout.tsx), so `user` is normally always set here — this
  // fallback just covers the brief instant between tapping "Sign Out" and
  // the gate bouncing back to /login.
  if (!user) return null;

  return (
    <View style={styles.profileRow}>
      {user.avatarUrl ? (
        <Image source={{ uri: user.avatarUrl }} style={styles.avatar} />
      ) : (
        <View style={[styles.avatar, styles.avatarFallback]}>
          <Ionicons name="person" size={22} color="#888" />
        </View>
      )}
      <View style={{ flex: 1, marginLeft: 12 }}>
        <Text style={styles.settingText} numberOfLines={1}>
          {user.name || user.email || "Signed in"}
        </Text>
        {user.email && (
          <Text style={styles.profileSub} numberOfLines={1}>
            {user.email}
          </Text>
        )}
      </View>
      <TouchableOpacity onPress={handleSignOut}>
        <Ionicons name="log-out-outline" size={22} color="#FF5252" />
      </TouchableOpacity>
    </View>
  );
}

export default function SettingsScreen() {
  const [backgroundAudio, setBackgroundAudio] = React.useState(true);
  const { downloads, clearAllMedia } = useMedia();
  const miniPlayerInset = useMiniPlayerInset();

  const handleClearCache = () => {
    if (downloads.length === 0) {
      Alert.alert("Nothing to clear", "You have no downloaded media.");
      return;
    }
    Alert.alert(
      "Clear Local Download Cache",
      `This permanently deletes all ${downloads.length} downloaded file(s), their tags, and all playlists from this device. This cannot be undone.`,
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Clear Everything",
          style: "destructive",
          onPress: () => clearAllMedia(),
        },
      ],
    );
  };

  return (
    <SafeAreaView style={styles.container} edges={["top", "left", "right"]}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => router.back()}>
          <Ionicons name="chevron-back" size={26} color="#FFF" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Settings</Text>
        <View style={{ width: 26 }} />
      </View>

      <View style={[styles.content, { paddingBottom: 16 + miniPlayerInset }]}>
        <Text style={styles.title}>Account</Text>
        <AccountSection />
        <DownloadEntitlementSection />

        <TouchableOpacity style={styles.settingRow} onPress={() => router.push("/history")}>
          <Text style={styles.settingText}>History</Text>
          <Ionicons name="chevron-forward" size={18} color="#888" />
        </TouchableOpacity>

        <Text style={[styles.title, { marginTop: 28 }]}>
          Playback Settings
        </Text>

        <View style={styles.settingRow}>
          <Text style={styles.settingText}>Background Playback</Text>
          <Switch
            value={backgroundAudio}
            onValueChange={setBackgroundAudio}
            trackColor={{ false: "#767577", true: "#1DB954" }}
          />
        </View>

        <TouchableOpacity style={styles.clearBtn} onPress={handleClearCache}>
          <Text style={{ color: "#FF5252", fontWeight: "bold" }}>
            Clear Local Download Cache
          </Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#121212" },
  header: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  headerTitle: { color: "#FFF", fontSize: 17, fontWeight: "bold" },
  content: { flex: 1, padding: 16 },
  title: { color: "#FFF", fontSize: 18, fontWeight: "bold", marginBottom: 20 },
  settingRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    backgroundColor: "#1E1E1E",
    padding: 16,
    borderRadius: 8,
    marginBottom: 12,
  },
  settingText: { color: "#FFF", fontSize: 14 },
  clearBtn: {
    backgroundColor: "#1E1E1E",
    padding: 16,
    borderRadius: 8,
    alignItems: "center",
    marginTop: 20,
  },
  profileRow: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#1E1E1E",
    padding: 12,
    borderRadius: 8,
    marginBottom: 12,
  },
  avatar: { width: 44, height: 44, borderRadius: 22 },
  avatarFallback: {
    backgroundColor: "#2A2A2A",
    alignItems: "center",
    justifyContent: "center",
  },
  profileSub: { color: "#888", fontSize: 12, marginTop: 2 },
  entitlementRow: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#1E1E1E",
    padding: 12,
    borderRadius: 8,
    marginBottom: 12,
  },
  buyBtn: {
    backgroundColor: "#1DB954",
    paddingHorizontal: 14,
    paddingVertical: 8,
    borderRadius: 20,
    alignItems: "center",
    justifyContent: "center",
  },
  buyBtnText: { color: "#121212", fontWeight: "bold", fontSize: 13 },
});
