import React, { useState, useEffect, useContext } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  FlatList,
  Modal,
  ScrollView,
  ActivityIndicator,
  Alert,
  StyleSheet,
  RefreshControl,
  SafeAreaView,
  StatusBar,
  Switch,
  Image,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { AuthContext } from "../context/AuthContext";
import { useTheme } from "../context/ThemeContext";
import {
  loginManage,
  getDomainInfo,
  createUser,
  deleteUser,
  changeUserPassword,
  toggleUserActive,
} from "../api/manage";

export default function ManageScreen() {
  const { colors } = useTheme();
  const {
    managedDomains,
    activeDomainSession,
    addManageDomain,
    switchManageDomain,
    removeManageDomain,
  } = useContext(AuthContext);

  // Login form state
  const [domainInput, setDomainInput] = useState("");
  const [emailInput, setEmailInput] = useState("");
  const [passInput, setPassInput] = useState("");
  const [isLoggingIn, setIsLoggingIn] = useState(false);

  // Multi-domain switcher modal
  const [isDomainSwitcherModal, setIsDomainSwitcherModal] = useState(false);
  const [isAddingNewDomain, setIsAddingNewDomain] = useState(false);

  // Domain Dashboard data
  const [domainInfo, setDomainInfo] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);

  // Modals
  const [isAddUserModal, setIsAddUserModal] = useState(false);
  const [newLocalPart, setNewLocalPart] = useState("");
  const [newName, setNewName] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [newQuota, setNewQuota] = useState("1024");
  const [isSubmittingUser, setIsSubmittingUser] = useState(false);

  // Change Password Modal
  const [selectedUserForPass, setSelectedUserForPass] = useState(null);
  const [changePassText, setChangePassText] = useState("");
  const [isSubmittingPass, setIsSubmittingPass] = useState(false);

  useEffect(() => {
    if (activeDomainSession) {
      loadDashboard();
    }
  }, [activeDomainSession]);

  const handleLogin = async () => {
    if (!domainInput || !passInput) {
      Alert.alert("Perhatian", "Nama domain dan kata sandi pemilik wajib diisi.");
      return;
    }
    setIsLoggingIn(true);
    try {
      const dom = domainInput.trim().toLowerCase();
      const em = emailInput.trim().toLowerCase() || `admin@${dom}`;
      const res = await loginManage(dom, passInput, em);
      if (res.success) {
        await addManageDomain(dom, passInput, em);
        setDomainInput("");
        setEmailInput("");
        setPassInput("");
        setIsAddingNewDomain(false);
        setIsDomainSwitcherModal(false);
      } else {
        Alert.alert("Gagal Masuk", res.error || "Akses ditolak. Periksa domain dan kata sandi.");
      }
    } catch (e) {
      Alert.alert("Kesalahan", e.message || "Gagal menghubungi server.");
    } finally {
      setIsLoggingIn(false);
    }
  };

  const loadDashboard = async () => {
    if (!activeDomainSession) return;
    setIsLoading(true);
    try {
      const res = await getDomainInfo(
        activeDomainSession.domain,
        activeDomainSession.password,
        activeDomainSession.email
      );
      if (res.success) {
        setDomainInfo(res);
      } else {
        Alert.alert("Sesi Berakhir", "Kata sandi salah atau sesi telah kedaluwarsa.");
        removeManageDomain(activeDomainSession.domain);
      }
    } catch (e) {
      console.log("Error loading domain info:", e);
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  };

  const handleRefresh = () => {
    setIsRefreshing(true);
    loadDashboard();
  };

  const handleCreateUser = async () => {
    if (!newLocalPart || !newPassword) {
      Alert.alert("Perhatian", "Username dan kata sandi akun wajib diisi.");
      return;
    }
    setIsSubmittingUser(true);
    try {
      const res = await createUser(
        activeDomainSession.domain,
        activeDomainSession.password,
        newLocalPart.trim(),
        newName.trim(),
        newPassword,
        parseInt(newQuota) || 1024
      );
      if (res.success) {
        Alert.alert("Sukses", "Akun email baru berhasil dibuat!");
        setIsAddUserModal(false);
        setNewLocalPart("");
        setNewName("");
        setNewPassword("");
        loadDashboard();
      } else {
        Alert.alert("Gagal", res.error || "Gagal membuat akun email.");
      }
    } catch (e) {
      Alert.alert("Kesalahan", e.message || "Terjadi gangguan jaringan.");
    } finally {
      setIsSubmittingUser(false);
    }
  };

  const handleChangePassword = async () => {
    if (!selectedUserForPass || !changePassText) {
      Alert.alert("Perhatian", "Kata sandi baru wajib diisi.");
      return;
    }
    setIsSubmittingPass(true);
    try {
      const res = await changeUserPassword(
        activeDomainSession.domain,
        activeDomainSession.password,
        selectedUserForPass.username,
        changePassText
      );
      if (res.success) {
        Alert.alert("Sukses", `Kata sandi untuk ${selectedUserForPass.username} berhasil diubah!`);
        setSelectedUserForPass(null);
        setChangePassText("");
        loadDashboard();
      } else {
        Alert.alert("Gagal", res.error || "Gagal mengubah kata sandi.");
      }
    } catch (e) {
      Alert.alert("Kesalahan", e.message || "Terjadi kesalahan.");
    } finally {
      setIsSubmittingPass(false);
    }
  };

  const handleDeleteUser = (userEmail) => {
    Alert.alert(
      "Konfirmasi Hapus",
      `Apakah Anda yakin ingin menghapus akun ${userEmail}? Semua data email di dalamnya akan terhapus.`,
      [
        { text: "Batal", style: "cancel" },
        {
          text: "Hapus Permanen",
          style: "destructive",
          onPress: async () => {
            try {
              const res = await deleteUser(activeDomainSession.domain, activeDomainSession.password, userEmail);
              if (res.success) {
                Alert.alert("Berhasil", "Akun email berhasil dihapus.");
                loadDashboard();
              } else {
                Alert.alert("Gagal", res.error || "Gagal menghapus akun.");
              }
            } catch (e) {
              Alert.alert("Kesalahan", "Gagal menghubungi server.");
            }
          },
        },
      ]
    );
  };

  const handleToggleActive = async (userEmail, currentActive) => {
    try {
      await toggleUserActive(activeDomainSession.domain, activeDomainSession.password, userEmail, !currentActive);
      loadDashboard();
    } catch (e) {
      Alert.alert("Kesalahan", "Gagal memperbarui status aktif akun.");
    }
  };

  // 1. Unauthenticated Login Screen
  if (!activeDomainSession) {
    return (
      <SafeAreaView style={[styles.container, { backgroundColor: colors.bg }]}>
        <StatusBar barStyle="light-content" />
        <ScrollView contentContainerStyle={styles.authScroll}>
          <View style={styles.authHeader}>
            <Image
              source={require("../assets/logo.png")}
              style={styles.logoImage}
              resizeMode="contain"
            />
            <Text style={[styles.title, { color: colors.text }]}>Kelola Domain</Text>
            <Text style={[styles.subtitle, { color: colors.textMuted }]}>
              Mendukung multi-domain kustom dalam satu aplikasi
            </Text>
          </View>

          <View style={[styles.authCard, { backgroundColor: colors.card, borderColor: colors.cardBorder }]}>
            <Text style={[styles.label, { color: colors.textMuted }]}>Nama Domain</Text>
            <TextInput
              style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
              placeholder="contoh.com"
              placeholderTextColor={colors.textDim}
              value={domainInput}
              onChangeText={setDomainInput}
              autoCapitalize="none"
            />

            <Text style={[styles.label, { color: colors.textMuted, marginTop: 14 }]}>Email Pemilik Domain</Text>
            <TextInput
              style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
              placeholder="admin@contoh.com (opsional)"
              placeholderTextColor={colors.textDim}
              value={emailInput}
              onChangeText={setEmailInput}
              autoCapitalize="none"
              keyboardType="email-address"
            />

            <Text style={[styles.label, { color: colors.textMuted, marginTop: 14 }]}>Kata Sandi Pemilik</Text>
            <TextInput
              style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
              placeholder="••••••••"
              placeholderTextColor={colors.textDim}
              value={passInput}
              onChangeText={setPassInput}
              secureTextEntry
            />

            <TouchableOpacity
              style={[styles.primaryButton, { backgroundColor: colors.primary }]}
              onPress={handleLogin}
              disabled={isLoggingIn}
            >
              {isLoggingIn ? (
                <ActivityIndicator color="#fff" />
              ) : (
                <Text style={styles.buttonText}>Buka Panel Domain</Text>
              )}
            </TouchableOpacity>
          </View>
        </ScrollView>
      </SafeAreaView>
    );
  }

  const mailboxes = domainInfo?.mailboxes || [];
  const maxMailboxes = domainInfo?.max_mailboxes || 3;

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

      {/* Top Header with Multi-Domain Selector */}
      <View style={[styles.topBar, { borderBottomColor: colors.cardBorder }]}>
        <TouchableOpacity
          style={styles.domainSelectorBtn}
          onPress={() => setIsDomainSwitcherModal(true)}
          activeOpacity={0.7}
        >
          <View style={[styles.avatar, { backgroundColor: colors.primary }]}>
            <Ionicons name="globe-outline" size={20} color="#fff" />
          </View>
          <View>
            <View style={{ flexDirection: "row", alignItems: "center", gap: 4 }}>
              <Text style={[styles.userName, { color: colors.text }]}>{activeDomainSession.domain}</Text>
              <Ionicons name="chevron-down" size={14} color={colors.textMuted} />
            </View>
            <Text style={[styles.userStatus, { color: colors.primary }]}>
              {mailboxes.length} / {maxMailboxes} Akun • {managedDomains.length} Domain Disimpan
            </Text>
          </View>
        </TouchableOpacity>

        <View style={styles.topActions}>
          <TouchableOpacity onPress={handleRefresh} style={styles.iconBtn}>
            <Ionicons name="refresh" size={20} color={colors.textMuted} />
          </TouchableOpacity>
          <TouchableOpacity onPress={() => setIsDomainSwitcherModal(true)} style={styles.iconBtn}>
            <Ionicons name="layers-outline" size={22} color={colors.primary} />
          </TouchableOpacity>
        </View>
      </View>

      <ScrollView
        refreshControl={<RefreshControl refreshing={isRefreshing} onRefresh={handleRefresh} tintColor={colors.primary} />}
        contentContainerStyle={styles.mainScroll}
      >
        {/* DNS Health Status Card */}
        <View style={[styles.dnsCard, { backgroundColor: colors.card, borderColor: colors.cardBorder }]}>
          <View style={styles.dnsHeader}>
            <View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
              <Ionicons name="shield-checkmark" size={18} color={colors.primary} />
              <Text style={[styles.dnsTitle, { color: colors.text }]}>Status DNS & Otentikasi</Text>
            </View>
            <View style={[styles.badgePill, { backgroundColor: colors.primaryLight }]}>
              <Text style={[styles.badgePillText, { color: colors.primary }]}>● Terhubung</Text>
            </View>
          </View>

          <View style={styles.dnsRow}>
            <View style={[styles.dnsChip, { backgroundColor: colors.subCard }]}>
              <Text style={[styles.dnsChipLabel, { color: colors.textMuted }]}>MX Record</Text>
              <Text style={[styles.dnsChipValue, { color: colors.primary }]}>10 mail.ruang.email</Text>
            </View>
            <View style={[styles.dnsChip, { backgroundColor: colors.subCard }]}>
              <Text style={[styles.dnsChipLabel, { color: colors.textMuted }]}>SPF</Text>
              <Text style={[styles.dnsChipValue, { color: colors.primary }]}>Valid (4 Node)</Text>
            </View>
          </View>

          <View style={styles.dnsRow}>
            <View style={[styles.dnsChip, { backgroundColor: colors.subCard }]}>
              <Text style={[styles.dnsChipLabel, { color: colors.textMuted }]}>DKIM</Text>
              <Text style={[styles.dnsChipValue, { color: colors.primary }]}>2048-bit RSA Valid</Text>
            </View>
            <View style={[styles.dnsChip, { backgroundColor: colors.subCard }]}>
              <Text style={[styles.dnsChipLabel, { color: colors.textMuted }]}>DMARC</Text>
              <Text style={[styles.dnsChipValue, { color: colors.primary }]}>Quarantine Aktif</Text>
            </View>
          </View>
        </View>

        {/* Action Header */}
        <View style={styles.actionHeader}>
          <Text style={[styles.sectionTitle, { color: colors.text }]}>Daftar Akun Email</Text>
          <TouchableOpacity
            style={[styles.addBtn, { backgroundColor: colors.primary }]}
            onPress={() => setIsAddUserModal(true)}
            disabled={mailboxes.length >= maxMailboxes}
          >
            <Ionicons name="person-add-outline" size={16} color="#fff" />
            <Text style={styles.addBtnText}>Buat Akun</Text>
          </TouchableOpacity>
        </View>

        {/* Mailbox List */}
        {isLoading && !isRefreshing ? (
          <ActivityIndicator size="large" color={colors.primary} style={{ marginTop: 30 }} />
        ) : mailboxes.length === 0 ? (
          <View style={styles.emptyBox}>
            <Text style={[styles.emptyText, { color: colors.textMuted }]}>Belum ada akun email dibuat.</Text>
          </View>
        ) : (
          mailboxes.map((user) => {
            const isActive = user.active === 1 || user.active === true;
            return (
              <View
                key={user.username}
                style={[styles.userCard, { backgroundColor: colors.card, borderColor: colors.cardBorder }]}
              >
                <View style={styles.userCardHeader}>
                  <View style={[styles.userAvatar, { backgroundColor: colors.primaryLight }]}>
                    <Text style={[styles.userAvatarText, { color: colors.primary }]}>
                      {user.username.charAt(0).toUpperCase()}
                    </Text>
                  </View>

                  <View style={{ flex: 1 }}>
                    <Text style={[styles.userCardEmail, { color: colors.text }]}>{user.username}</Text>
                    <Text style={[styles.userCardName, { color: colors.textDim }]}>
                      {user.name || "Pengguna Email"} • Kuota: {user.quota_mb || 1024} MB
                    </Text>
                  </View>

                  <Switch
                    value={isActive}
                    onValueChange={() => handleToggleActive(user.username, isActive)}
                    trackColor={{ false: colors.cardBorder, true: colors.primaryDark }}
                    thumbColor={isActive ? colors.primary : "#94a3b8"}
                  />
                </View>

                <View style={styles.userCardFooter}>
                  <TouchableOpacity
                    style={[styles.smallBtn, { backgroundColor: colors.subCard }]}
                    onPress={() => {
                      setSelectedUserForPass(user);
                      setChangePassText("");
                    }}
                  >
                    <Ionicons name="key-outline" size={14} color={colors.textMuted} />
                    <Text style={[styles.smallBtnText, { color: colors.textMuted }]}>Ganti Sandi</Text>
                  </TouchableOpacity>

                  <TouchableOpacity
                    style={[styles.smallBtn, { backgroundColor: colors.dangerLight }]}
                    onPress={() => handleDeleteUser(user.username)}
                  >
                    <Ionicons name="trash-outline" size={14} color={colors.danger} />
                    <Text style={[styles.smallBtnText, { color: colors.danger }]}>Hapus</Text>
                  </TouchableOpacity>
                </View>
              </View>
            );
          })
        )}
      </ScrollView>

      {/* Multi-Domain Switcher Modal */}
      <Modal visible={isDomainSwitcherModal} animationType="slide" presentationStyle="pageSheet">
        <SafeAreaView style={[styles.modalContainer, { backgroundColor: colors.bg }]}>
          <View style={[styles.modalHeader, { borderBottomColor: colors.cardBorder }]}>
            <TouchableOpacity onPress={() => setIsDomainSwitcherModal(false)} style={styles.iconBtn}>
              <Ionicons name="close" size={24} color={colors.text} />
            </TouchableOpacity>
            <Text style={[styles.modalTitle, { color: colors.text }]}>Kelola Multi-Domain</Text>
            <View style={{ width: 24 }} />
          </View>

          <ScrollView style={{ padding: 16 }}>
            <Text style={[styles.sectionHeading, { color: colors.textMuted }]}>
              DOMAIN DISIMPAN ({managedDomains.length})
            </Text>

            {managedDomains.map((dom) => {
              const isCurrent = dom.domain.toLowerCase() === activeDomainSession.domain.toLowerCase();
              return (
                <View
                  key={dom.domain}
                  style={[
                    styles.domainCard,
                    {
                      backgroundColor: isCurrent ? colors.subCard : colors.card,
                      borderColor: isCurrent ? colors.primary : colors.cardBorder,
                    },
                  ]}
                >
                  <TouchableOpacity
                    style={{ flex: 1, flexDirection: "row", alignItems: "center", gap: 12 }}
                    onPress={() => {
                      switchManageDomain(dom.domain);
                      setIsDomainSwitcherModal(false);
                    }}
                  >
                    <View style={[styles.avatar, { backgroundColor: isCurrent ? colors.primary : colors.cardBorder }]}>
                      <Ionicons name="globe" size={18} color="#fff" />
                    </View>
                    <View style={{ flex: 1 }}>
                      <Text style={[styles.domainNameText, { color: colors.text, fontWeight: isCurrent ? "bold" : "600" }]}>
                        {dom.domain}
                      </Text>
                      <Text style={[styles.domainOwnerText, { color: colors.textDim }]}>
                        {dom.email} {isCurrent ? "• Sedang Dikelola" : ""}
                      </Text>
                    </View>
                  </TouchableOpacity>

                  {isCurrent ? (
                    <Ionicons name="checkmark-circle" size={22} color={colors.primary} />
                  ) : (
                    <TouchableOpacity
                      onPress={() => removeManageDomain(dom.domain)}
                      style={{ padding: 6 }}
                    >
                      <Ionicons name="close-circle-outline" size={20} color={colors.danger} />
                    </TouchableOpacity>
                  )}
                </View>
              );
            })}

            {/* Add New Domain Form */}
            {isAddingNewDomain ? (
              <View style={[styles.authCard, { backgroundColor: colors.card, borderColor: colors.cardBorder, marginTop: 16 }]}>
                <Text style={[styles.cardTitle, { color: colors.text }]}>Hubungkan Domain Baru</Text>
                <Text style={[styles.cardSub, { color: colors.textMuted }]}>
                  Masukkan domain dan kata sandi pemiliknya
                </Text>

                <Text style={[styles.label, { color: colors.textMuted }]}>Nama Domain</Text>
                <TextInput
                  style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
                  placeholder="domainlain.com"
                  placeholderTextColor={colors.textDim}
                  value={domainInput}
                  onChangeText={setDomainInput}
                  autoCapitalize="none"
                />

                <Text style={[styles.label, { color: colors.textMuted, marginTop: 12 }]}>Email Pemilik (Opsional)</Text>
                <TextInput
                  style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
                  placeholder="admin@domainlain.com"
                  placeholderTextColor={colors.textDim}
                  value={emailInput}
                  onChangeText={setEmailInput}
                  autoCapitalize="none"
                  keyboardType="email-address"
                />

                <Text style={[styles.label, { color: colors.textMuted, marginTop: 12 }]}>Kata Sandi Pemilik</Text>
                <TextInput
                  style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
                  placeholder="••••••••"
                  placeholderTextColor={colors.textDim}
                  value={passInput}
                  onChangeText={setPassInput}
                  secureTextEntry
                />

                <View style={{ flexDirection: "row", gap: 10, marginTop: 16 }}>
                  <TouchableOpacity
                    style={[styles.primaryButton, { flex: 1, backgroundColor: colors.subCard }]}
                    onPress={() => setIsAddingNewDomain(false)}
                  >
                    <Text style={[styles.buttonText, { color: colors.textMuted }]}>Batal</Text>
                  </TouchableOpacity>

                  <TouchableOpacity
                    style={[styles.primaryButton, { flex: 2, backgroundColor: colors.primary }]}
                    onPress={handleLogin}
                    disabled={isLoggingIn}
                  >
                    {isLoggingIn ? (
                      <ActivityIndicator color="#fff" />
                    ) : (
                      <Text style={styles.buttonText}>Hubungkan</Text>
                    )}
                  </TouchableOpacity>
                </View>
              </View>
            ) : (
              <TouchableOpacity
                style={[styles.addDomainBtn, { borderColor: colors.primary, backgroundColor: colors.primaryLight }]}
                onPress={() => setIsAddingNewDomain(true)}
              >
                <Ionicons name="add-circle-outline" size={18} color={colors.primary} />
                <Text style={[styles.addDomainBtnText, { color: colors.primary }]}>
                  + Hubungkan Domain Lain (Multi-Domain)
                </Text>
              </TouchableOpacity>
            )}

            <TouchableOpacity
              style={[styles.logoutActiveBtn, { borderColor: colors.dangerLight, marginTop: 24 }]}
              onPress={() => {
                removeManageDomain(activeDomainSession.domain);
                setIsDomainSwitcherModal(false);
              }}
            >
              <Ionicons name="log-out-outline" size={18} color={colors.danger} />
              <Text style={{ color: colors.danger, fontWeight: "bold", fontSize: 13 }}>
                Hapus Sesi {activeDomainSession.domain}
              </Text>
            </TouchableOpacity>
          </ScrollView>
        </SafeAreaView>
      </Modal>

      {/* Modal Add Mailbox */}
      <Modal visible={isAddUserModal} animationType="slide" presentationStyle="pageSheet">
        <SafeAreaView style={[styles.modalContainer, { backgroundColor: colors.bg }]}>
          <View style={[styles.modalHeader, { borderBottomColor: colors.cardBorder }]}>
            <TouchableOpacity onPress={() => setIsAddUserModal(false)} style={styles.iconBtn}>
              <Ionicons name="close" size={24} color={colors.text} />
            </TouchableOpacity>
            <Text style={[styles.modalTitle, { color: colors.text }]}>Tambah Akun Email</Text>
            <View style={{ width: 24 }} />
          </View>

          <ScrollView style={styles.modalForm}>
            <Text style={[styles.label, { color: colors.textMuted }]}>Nama Pengguna (Username)</Text>
            <View style={styles.inputWithSuffix}>
              <TextInput
                style={[styles.input, { flex: 1, backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
                placeholder="nama.anda"
                placeholderTextColor={colors.textDim}
                value={newLocalPart}
                onChangeText={setNewLocalPart}
                autoCapitalize="none"
              />
              <Text style={[styles.inputSuffixText, { color: colors.primary }]}>@{activeDomainSession.domain}</Text>
            </View>

            <Text style={[styles.label, { color: colors.textMuted, marginTop: 14 }]}>Nama Lengkap / Departemen</Text>
            <TextInput
              style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
              placeholder="Contoh: Customer Care"
              placeholderTextColor={colors.textDim}
              value={newName}
              onChangeText={setNewName}
            />

            <Text style={[styles.label, { color: colors.textMuted, marginTop: 14 }]}>Kata Sandi Akun</Text>
            <TextInput
              style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
              placeholder="Minimal 6 karakter..."
              placeholderTextColor={colors.textDim}
              value={newPassword}
              onChangeText={setNewPassword}
              secureTextEntry
            />

            <Text style={[styles.label, { color: colors.textMuted, marginTop: 14 }]}>Kapasitas Kuota Penyimpanan (MB)</Text>
            <TextInput
              style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
              placeholder="1024"
              placeholderTextColor={colors.textDim}
              value={newQuota}
              onChangeText={setNewQuota}
              keyboardType="number-pad"
            />

            <TouchableOpacity
              style={[styles.primaryButton, { backgroundColor: colors.primary, marginTop: 24 }]}
              onPress={handleCreateUser}
              disabled={isSubmittingUser}
            >
              {isSubmittingUser ? (
                <ActivityIndicator color="#fff" />
              ) : (
                <Text style={styles.buttonText}>Buat Akun Sekarang</Text>
              )}
            </TouchableOpacity>
          </ScrollView>
        </SafeAreaView>
      </Modal>

      {/* Modal Change Password */}
      <Modal visible={!!selectedUserForPass} animationType="fade" transparent>
        <View style={styles.modalOverlay}>
          <View style={[styles.dialogCard, { backgroundColor: colors.card, borderColor: colors.cardBorder }]}>
            <Text style={[styles.dialogTitle, { color: colors.text }]}>Ganti Kata Sandi</Text>
            <Text style={[styles.dialogSub, { color: colors.textMuted }]}>
              {selectedUserForPass?.username}
            </Text>

            <TextInput
              style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text, marginVertical: 14 }]}
              placeholder="Kata sandi baru..."
              placeholderTextColor={colors.textDim}
              value={changePassText}
              onChangeText={setChangePassText}
              secureTextEntry
            />

            <View style={styles.dialogActions}>
              <TouchableOpacity
                onPress={() => setSelectedUserForPass(null)}
                style={[styles.dialogBtn, { backgroundColor: colors.subCard }]}
              >
                <Text style={[styles.dialogBtnText, { color: colors.textMuted }]}>Batal</Text>
              </TouchableOpacity>

              <TouchableOpacity
                onPress={handleChangePassword}
                disabled={isSubmittingPass}
                style={[styles.dialogBtn, { backgroundColor: colors.primary }]}
              >
                {isSubmittingPass ? (
                  <ActivityIndicator color="#fff" size="small" />
                ) : (
                  <Text style={[styles.dialogBtnText, { color: "#fff" }]}>Simpan</Text>
                )}
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  authScroll: { padding: 24, justifyContent: "center", minHeight: "100%" },
  authHeader: { alignItems: "center", marginBottom: 24 },
  logoImage: { width: 140, height: 140, marginBottom: 12 },
  title: { fontSize: 24, fontWeight: "800", marginBottom: 6 },
  subtitle: { fontSize: 13, textAlign: "center", lineHeight: 18 },
  authCard: { borderRadius: 16, padding: 20, borderWidth: 1 },
  label: { fontSize: 12, fontWeight: "600", marginBottom: 6 },
  input: { borderWidth: 1, borderRadius: 10, paddingHorizontal: 14, paddingVertical: 12, fontSize: 14 },
  primaryButton: { borderRadius: 12, paddingVertical: 14, alignItems: "center" },
  buttonText: { color: "#fff", fontWeight: "700", fontSize: 15 },
  topBar: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", paddingHorizontal: 16, paddingVertical: 10, borderBottomWidth: 1 },
  domainSelectorBtn: { flexDirection: "row", alignItems: "center", gap: 10, flex: 1 },
  avatar: { width: 38, height: 38, borderRadius: 19, alignItems: "center", justifyContent: "center" },
  userName: { fontSize: 15, fontWeight: "700" },
  userStatus: { fontSize: 11, fontWeight: "600" },
  topActions: { flexDirection: "row", gap: 6, alignItems: "center" },
  iconBtn: { padding: 6 },
  mainScroll: { padding: 16 },
  dnsCard: { borderRadius: 16, padding: 16, borderWidth: 1, marginBottom: 20 },
  dnsHeader: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginBottom: 12 },
  dnsTitle: { fontSize: 14, fontWeight: "700" },
  badgePill: { paddingHorizontal: 10, paddingVertical: 4, borderRadius: 12 },
  badgePillText: { fontSize: 11, fontWeight: "bold" },
  dnsRow: { flexDirection: "row", gap: 10, marginBottom: 10 },
  dnsChip: { flex: 1, padding: 10, borderRadius: 10 },
  dnsChipLabel: { fontSize: 11, fontWeight: "600", marginBottom: 2 },
  dnsChipValue: { fontSize: 12, fontWeight: "bold" },
  actionHeader: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginBottom: 14 },
  sectionTitle: { fontSize: 16, fontWeight: "bold" },
  addBtn: { flexDirection: "row", alignItems: "center", gap: 6, paddingHorizontal: 14, paddingVertical: 8, borderRadius: 10 },
  addBtnText: { color: "#fff", fontWeight: "bold", fontSize: 12 },
  emptyBox: { padding: 40, alignItems: "center" },
  emptyText: { fontSize: 14 },
  userCard: { borderRadius: 14, padding: 14, borderWidth: 1, marginBottom: 12 },
  userCardHeader: { flexDirection: "row", alignItems: "center", gap: 12 },
  userAvatar: { width: 40, height: 40, borderRadius: 20, alignItems: "center", justifyContent: "center" },
  userAvatarText: { fontSize: 16, fontWeight: "bold" },
  userCardEmail: { fontSize: 14, fontWeight: "700" },
  userCardName: { fontSize: 12, marginTop: 2 },
  userCardFooter: { flexDirection: "row", justifyContent: "flex-end", gap: 10, marginTop: 12, paddingTop: 10, borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: "#334155" },
  smallBtn: { flexDirection: "row", alignItems: "center", gap: 4, paddingHorizontal: 10, paddingVertical: 6, borderRadius: 8 },
  smallBtnText: { fontSize: 11, fontWeight: "bold" },
  modalContainer: { flex: 1 },
  modalHeader: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", paddingHorizontal: 16, paddingVertical: 14, borderBottomWidth: 1 },
  modalTitle: { fontSize: 16, fontWeight: "bold" },
  modalForm: { padding: 16 },
  inputWithSuffix: { flexDirection: "row", alignItems: "center", gap: 8 },
  inputSuffixText: { fontSize: 14, fontWeight: "bold" },
  modalOverlay: { flex: 1, backgroundColor: "rgba(0,0,0,0.6)", justifyContent: "center", padding: 24 },
  dialogCard: { borderRadius: 16, padding: 20, borderWidth: 1 },
  dialogTitle: { fontSize: 16, fontWeight: "bold" },
  dialogSub: { fontSize: 12, marginTop: 2 },
  dialogActions: { flexDirection: "row", justifyContent: "flex-end", gap: 10 },
  dialogBtn: { paddingHorizontal: 16, paddingVertical: 10, borderRadius: 10 },
  dialogBtnText: { fontSize: 13, fontWeight: "bold" },
  sectionHeading: { fontSize: 11, fontWeight: "bold", letterSpacing: 1, marginBottom: 10 },
  domainCard: { flexDirection: "row", alignItems: "center", padding: 14, borderRadius: 14, borderWidth: 1, marginBottom: 10 },
  domainNameText: { fontSize: 15 },
  domainOwnerText: { fontSize: 12, marginTop: 2 },
  addDomainBtn: { flexDirection: "row", alignItems: "center", justifyContent: "center", gap: 8, paddingVertical: 14, borderRadius: 14, borderWidth: 1, marginTop: 12 },
  addDomainBtnText: { fontWeight: "bold", fontSize: 13 },
  logoutActiveBtn: { flexDirection: "row", alignItems: "center", justifyContent: "center", gap: 6, paddingVertical: 12, borderRadius: 12, borderWidth: 1 },
  cardTitle: { fontSize: 16, fontWeight: "bold" },
  cardSub: { fontSize: 12, marginTop: 2, marginBottom: 14 },
});
