import React, { useState, useContext } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  Alert,
  StyleSheet,
  SafeAreaView,
  StatusBar,
  Image,
  ActivityIndicator,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { AuthContext } from "../context/AuthContext";
import { useTheme } from "../context/ThemeContext";
import { getServerUrl, setServerUrl } from "../api/config";
import { checkForUpdates, CURRENT_APP_VERSION } from "../services/UpdateService";
import UpdateModal from "../components/UpdateModal";

export default function SettingsScreen() {
  const { colors } = useTheme();
  const { webmailUser, activeAccount, activeDomainSession, removeWebmailAccount, removeManageDomain } = useContext(AuthContext);

  const [customServer, setCustomServer] = useState(getServerUrl());
  const [isCheckingUpdate, setIsCheckingUpdate] = useState(false);
  const [updateInfo, setUpdateInfo] = useState(null);
  const [showUpdateModal, setShowUpdateModal] = useState(false);

  const handleSaveServer = () => {
    if (!customServer) return;
    setServerUrl(customServer.trim());
    Alert.alert("Tersimpan", `Alamat server email disetel ke: ${customServer.trim()}`);
  };

  const handleCheckUpdate = async () => {
    setIsCheckingUpdate(true);
    try {
      const res = await checkForUpdates();
      if (res.updateAvailable) {
        setUpdateInfo(res);
        setShowUpdateModal(true);
      } else {
        Alert.alert("Versi Terbaru", `Aplikasi Anda sudah menggunakan versi paling mutakhir (v${CURRENT_APP_VERSION}).`);
      }
    } catch (e) {
      Alert.alert("Kesalahan", "Gagal memeriksa pembaruan server.");
    } finally {
      setIsCheckingUpdate(false);
    }
  };

  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.bg }]}>
      <StatusBar barStyle="light-content" />

      <View style={[styles.topBar, { borderBottomColor: colors.cardBorder }]}>
        <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
          <View style={[styles.avatar, { backgroundColor: colors.primary }]}>
            <Ionicons name="settings-sharp" size={20} color="#fff" />
          </View>
          <Text style={[styles.topTitle, { color: colors.text }]}>Pengaturan & Status Server</Text>
        </View>
      </View>

      <ScrollView contentContainerStyle={styles.scrollContent}>
        {/* App Logo & OTA Update Card */}
        <View style={[styles.card, { backgroundColor: colors.card, borderColor: colors.cardBorder, alignItems: "center" }]}>
          <Image
            source={require("../assets/logo.png")}
            style={styles.logoImage}
            resizeMode="contain"
          />
          <Text style={[styles.appName, { color: colors.text }]}>Ruang.Email SuperApp</Text>
          <Text style={[styles.versionText, { color: colors.primary }]}>Versi {CURRENT_APP_VERSION} (Build 2026.09)</Text>

          <TouchableOpacity
            style={[styles.otaBtn, { backgroundColor: colors.primaryLight, borderColor: colors.primary }]}
            onPress={handleCheckUpdate}
            disabled={isCheckingUpdate}
          >
            {isCheckingUpdate ? (
              <ActivityIndicator color={colors.primary} size="small" />
            ) : (
              <>
                <Ionicons name="cloud-download-outline" size={18} color={colors.primary} />
                <Text style={[styles.otaBtnText, { color: colors.primary }]}>
                  Periksa Pembaruan (OTA Update)
                </Text>
              </>
            )}
          </TouchableOpacity>
        </View>

        {/* Cluster Health Status */}
        <View style={[styles.card, { backgroundColor: colors.card, borderColor: colors.cardBorder, marginTop: 16 }]}>
          <Text style={[styles.cardTitle, { color: colors.text }]}>Status 4-Node Mail Cluster</Text>
          <Text style={[styles.cardSub, { color: colors.textMuted }]}>
            Jaringan server email terdistribusi dengan sinkronisasi realtime
          </Text>

          <View style={styles.clusterNodeRow}>
            <View style={{ flexDirection: "row", alignItems: "center", gap: 10 }}>
              <View style={[styles.statusDot, { backgroundColor: colors.primary }]} />
              <View>
                <Text style={[styles.nodeName, { color: colors.text }]}>Node 1 (Frankfurt Master)</Text>
                <Text style={[styles.nodeIp, { color: colors.textDim }]}>154.12.117.162 • Primary DB & SMTP</Text>
              </View>
            </View>
            <Text style={[styles.statusText, { color: colors.primary }]}>Normal</Text>
          </View>

          <View style={styles.clusterNodeRow}>
            <View style={{ flexDirection: "row", alignItems: "center", gap: 10 }}>
              <View style={[styles.statusDot, { backgroundColor: colors.primary }]} />
              <View>
                <Text style={[styles.nodeName, { color: colors.text }]}>Node 2 (Jakarta Replica)</Text>
                <Text style={[styles.nodeIp, { color: colors.textDim }]}>178.83.181.180 • Low Latency ID</Text>
              </View>
            </View>
            <Text style={[styles.statusText, { color: colors.primary }]}>Normal</Text>
          </View>

          <View style={styles.clusterNodeRow}>
            <View style={{ flexDirection: "row", alignItems: "center", gap: 10 }}>
              <View style={[styles.statusDot, { backgroundColor: colors.primary }]} />
              <View>
                <Text style={[styles.nodeName, { color: colors.text }]}>Node 3 (Paris Replica)</Text>
                <Text style={[styles.nodeIp, { color: colors.textDim }]}>163.172.110.146 • High Availability EU</Text>
              </View>
            </View>
            <Text style={[styles.statusText, { color: colors.primary }]}>Normal</Text>
          </View>

          <View style={[styles.clusterNodeRow, { borderBottomWidth: 0 }]}>
            <View style={{ flexDirection: "row", alignItems: "center", gap: 10 }}>
              <View style={[styles.statusDot, { backgroundColor: colors.primary }]} />
              <View>
                <Text style={[styles.nodeName, { color: colors.text }]}>Node 4 (Singapore Replica)</Text>
                <Text style={[styles.nodeIp, { color: colors.textDim }]}>64.235.61.67 • Fast Routing APAC</Text>
              </View>
            </View>
            <Text style={[styles.statusText, { color: colors.primary }]}>Normal</Text>
          </View>
        </View>

        {/* Server Endpoint Config */}
        <View style={[styles.card, { backgroundColor: colors.card, borderColor: colors.cardBorder, marginTop: 16 }]}>
          <Text style={[styles.cardTitle, { color: colors.text }]}>Endpoint Server</Text>
          <Text style={[styles.cardSub, { color: colors.textMuted }]}>
            Gunakan host kustom atau default https://ruang.email
          </Text>

          <TextInput
            style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
            value={customServer}
            onChangeText={setCustomServer}
            autoCapitalize="none"
          />

          <TouchableOpacity
            style={[styles.smallBtn, { backgroundColor: colors.primary, marginTop: 10 }]}
            onPress={handleSaveServer}
          >
            <Text style={styles.smallBtnText}>Simpan Server</Text>
          </TouchableOpacity>
        </View>

        {/* Active Sessions */}
        <View style={[styles.card, { backgroundColor: colors.card, borderColor: colors.cardBorder, marginTop: 16 }]}>
          <Text style={[styles.cardTitle, { color: colors.text }]}>Sesi Aktif Saat Ini</Text>

          <View style={styles.sessionBox}>
            <Text style={[styles.sessionLabel, { color: colors.textMuted }]}>Akun Webmail:</Text>
            <Text style={[styles.sessionValue, { color: colors.text }]}>
              {activeAccount ? activeAccount.email : "(Belum Masuk)"}
            </Text>
            {activeAccount && (
              <TouchableOpacity onPress={() => removeWebmailAccount(activeAccount.email)} style={styles.logoutLink}>
                <Text style={{ color: colors.danger, fontWeight: "bold" }}>Hapus Sesi</Text>
              </TouchableOpacity>
            )}
          </View>

          <View style={[styles.sessionBox, { borderTopWidth: 1, borderTopColor: colors.cardBorder, paddingTop: 10, marginTop: 10 }]}>
            <Text style={[styles.sessionLabel, { color: colors.textMuted }]}>Domain Aktif:</Text>
            <Text style={[styles.sessionValue, { color: colors.text }]}>
              {activeDomainSession ? activeDomainSession.domain : "(Belum Masuk)"}
            </Text>
            {activeDomainSession && (
              <TouchableOpacity onPress={() => removeManageDomain(activeDomainSession.domain)} style={styles.logoutLink}>
                <Text style={{ color: colors.danger, fontWeight: "bold" }}>Hapus Sesi</Text>
              </TouchableOpacity>
            )}
          </View>
        </View>

        {/* Footer */}
        <View style={styles.footer}>
          <Text style={[styles.footerText, { color: colors.textDim }]}>
            Ruang.Email SuperApp (Android APK & iOS)
          </Text>
          <Text style={[styles.footerText, { color: colors.textDim }]}>
            Multi-Akun • Multi-Domain • Notifikasi HP • OTA Update
          </Text>
        </View>
      </ScrollView>

      {/* OTA Update Dialog */}
      <UpdateModal
        visible={showUpdateModal}
        updateInfo={updateInfo}
        onClose={() => setShowUpdateModal(false)}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  topBar: { paddingHorizontal: 16, paddingVertical: 14, borderBottomWidth: 1 },
  avatar: { width: 34, height: 34, borderRadius: 17, alignItems: "center", justifyContent: "center" },
  topTitle: { fontSize: 16, fontWeight: "bold" },
  scrollContent: { padding: 16 },
  card: { borderRadius: 16, padding: 18, borderWidth: 1 },
  logoImage: { width: 100, height: 100, marginBottom: 8 },
  appName: { fontSize: 18, fontWeight: "800" },
  versionText: { fontSize: 12, fontWeight: "bold", marginTop: 2, marginBottom: 12 },
  otaBtn: { flexDirection: "row", alignItems: "center", gap: 8, paddingHorizontal: 16, paddingVertical: 10, borderRadius: 20, borderWidth: 1 },
  otaBtnText: { fontSize: 12, fontWeight: "bold" },
  cardTitle: { fontSize: 16, fontWeight: "bold" },
  cardSub: { fontSize: 12, marginTop: 4, marginBottom: 16 },
  clusterNodeRow: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", paddingVertical: 12, borderBottomWidth: 1, borderBottomColor: "#1e293b" },
  statusDot: { width: 10, height: 10, borderRadius: 5 },
  nodeName: { fontSize: 13, fontWeight: "700" },
  nodeIp: { fontSize: 11, marginTop: 2 },
  statusText: { fontSize: 12, fontWeight: "bold" },
  input: { borderWidth: 1, borderRadius: 10, paddingHorizontal: 14, paddingVertical: 12, fontSize: 14 },
  smallBtn: { borderRadius: 10, paddingVertical: 10, alignItems: "center" },
  smallBtnText: { color: "#fff", fontWeight: "bold", fontSize: 13 },
  sessionBox: { flexDirection: "row", alignItems: "center", justifyContent: "space-between" },
  sessionLabel: { fontSize: 13 },
  sessionValue: { fontSize: 13, fontWeight: "bold", flex: 1, marginLeft: 8 },
  logoutLink: { paddingHorizontal: 10 },
  footer: { alignItems: "center", marginTop: 28, marginBottom: 20, gap: 4 },
  footerText: { fontSize: 11 },
});
