import React, { useState } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  ActivityIndicator,
  Alert,
  StyleSheet,
  SafeAreaView,
  StatusBar,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useTheme } from "../context/ThemeContext";
import { checkDomainAvailability, registerDomain } from "../api/register";

export default function RegisterScreen({ navigation }) {
  const { colors } = useTheme();

  // Form State
  const [domain, setDomain] = useState("");
  const [localPart, setLocalPart] = useState("admin");
  const [adminName, setAdminName] = useState("");
  const [adminPassword, setAdminPassword] = useState("");

  // UI Flow State
  const [isChecking, setIsChecking] = useState(false);
  const [checkResult, setCheckResult] = useState(null);
  const [isRegistering, setIsRegistering] = useState(false);
  const [registeredData, setRegisteredData] = useState(null);

  const handleCheckDomain = async () => {
    if (!domain) {
      Alert.alert("Perhatian", "Masukkan nama domain yang ingin didaftarkan.");
      return;
    }
    const cleanDomain = domain.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/\/+$/, "");
    setDomain(cleanDomain);
    setIsChecking(true);
    setCheckResult(null);

    try {
      const res = await checkDomainAvailability(cleanDomain);
      setCheckResult(res);
      if (!res.available) {
        Alert.alert("Domain Sudah Terdaftar", res.message || "Domain ini sudah ada di sistem.");
      }
    } catch (e) {
      Alert.alert("Kesalahan", e.message || "Gagal memeriksa domain.");
    } finally {
      setIsChecking(false);
    }
  };

  const handleRegister = async () => {
    if (!domain || !localPart || !adminPassword) {
      Alert.alert("Perhatian", "Domain, username, dan kata sandi wajib diisi.");
      return;
    }
    setIsRegistering(true);
    try {
      const res = await registerDomain(
        domain.trim().toLowerCase(),
        localPart.trim().toLowerCase(),
        adminName.trim() || "Administrator",
        adminPassword
      );

      if (res.success) {
        setRegisteredData(res);
        Alert.alert("Pendaftaran Berhasil!", `Domain ${domain} berhasil didaftarkan ke cluster Ruang.Email.`);
      } else {
        Alert.alert("Gagal", res.error || "Gagal mendaftarkan domain.");
      }
    } catch (e) {
      Alert.alert("Kesalahan", e.message || "Terjadi kesalahan jaringan.");
    } finally {
      setIsRegistering(false);
    }
  };

  const handleReset = () => {
    setRegisteredData(null);
    setCheckResult(null);
    setDomain("");
    setLocalPart("admin");
    setAdminName("");
    setAdminPassword("");
  };

  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="add-circle" size={22} color="#fff" />
          </View>
          <Text style={[styles.topTitle, { color: colors.text }]}>Daftar Domain Baru</Text>
        </View>
      </View>

      <ScrollView contentContainerStyle={styles.scrollContent}>
        {/* Step 3: Success DNS Setup View */}
        {registeredData ? (
          <View>
            <View style={[styles.successBanner, { backgroundColor: colors.primaryLight, borderColor: colors.primary }]}>
              <Ionicons name="checkmark-circle" size={32} color={colors.primary} />
              <View style={{ flex: 1 }}>
                <Text style={[styles.successTitle, { color: colors.primary }]}>Domain Berhasil Didaftarkan!</Text>
                <Text style={[styles.successSub, { color: colors.text }]}>
                  Pasang 4 Record DNS berikut di Cloudflare / DNS Manager domain Anda:
                </Text>
              </View>
            </View>

            {/* DNS Records Table */}
            <View style={[styles.card, { backgroundColor: colors.card, borderColor: colors.cardBorder }]}>
              <Text style={[styles.recordHeader, { color: colors.text }]}>1. MX Record (Penerimaan Email)</Text>
              <View style={[styles.recordBox, { backgroundColor: colors.subCard }]}>
                <Text style={[styles.recordRow, { color: colors.textMuted }]}>Type: <Text style={{ color: colors.primary, fontWeight: "bold" }}>MX</Text> • Priority: <Text style={{ color: colors.primary, fontWeight: "bold" }}>10</Text></Text>
                <Text style={[styles.recordRow, { color: colors.textMuted }]}>Host: <Text style={{ color: colors.text }}>@</Text></Text>
                <Text style={[styles.recordValue, { color: colors.text }]}>mail.ruang.email</Text>
              </View>

              <Text style={[styles.recordHeader, { color: colors.text, marginTop: 14 }]}>2. SPF Record (Otorisasi Pengirim)</Text>
              <View style={[styles.recordBox, { backgroundColor: colors.subCard }]}>
                <Text style={[styles.recordRow, { color: colors.textMuted }]}>Type: <Text style={{ color: colors.primary, fontWeight: "bold" }}>TXT</Text> • Host: <Text style={{ color: colors.text }}>@</Text></Text>
                <Text style={[styles.recordValue, { color: colors.text }]}>
                  v=spf1 mx a:mail.ruang.email ip4:154.12.117.162 ip4:178.83.181.180 ip4:163.172.110.146 ip4:64.235.61.67 ~all
                </Text>
              </View>

              <Text style={[styles.recordHeader, { color: colors.text, marginTop: 14 }]}>3. DKIM Record (Tanda Tangan Digital 2048-bit)</Text>
              <View style={[styles.recordBox, { backgroundColor: colors.subCard }]}>
                <Text style={[styles.recordRow, { color: colors.textMuted }]}>Type: <Text style={{ color: colors.primary, fontWeight: "bold" }}>TXT</Text> • Host: <Text style={{ color: colors.primary, fontWeight: "bold" }}>dkim._domainkey</Text></Text>
                <Text style={[styles.recordValue, { color: colors.text }]}>
                  {registeredData.dkim_record || "v=DKIM1; k=rsa; p=MIIBIjANBgkq..."}
                </Text>
              </View>

              <Text style={[styles.recordHeader, { color: colors.text, marginTop: 14 }]}>4. DMARC Record (Proteksi Anti-Spoofing)</Text>
              <View style={[styles.recordBox, { backgroundColor: colors.subCard }]}>
                <Text style={[styles.recordRow, { color: colors.textMuted }]}>Type: <Text style={{ color: colors.primary, fontWeight: "bold" }}>TXT</Text> • Host: <Text style={{ color: colors.text }}>_dmarc</Text></Text>
                <Text style={[styles.recordValue, { color: colors.text }]}>
                  v=DMARC1; p=quarantine; sp=quarantine; aspf=r; adkim=r;
                </Text>
              </View>

              <TouchableOpacity
                style={[styles.primaryBtn, { backgroundColor: colors.primary, marginTop: 20 }]}
                onPress={handleReset}
              >
                <Text style={styles.primaryBtnText}>Daftarkan Domain Lain</Text>
              </TouchableOpacity>
            </View>
          </View>
        ) : (
          /* Step 1 & 2: Search & Register Form */
          <View>
            <View style={[styles.card, { backgroundColor: colors.card, borderColor: colors.cardBorder }]}>
              <Text style={[styles.cardTitle, { color: colors.text }]}>Cek Ketersediaan Domain</Text>
              <Text style={[styles.cardSub, { color: colors.textMuted }]}>
                Gunakan domain Anda sendiri untuk memiliki email bisnis kustom
              </Text>

              <View style={styles.searchRow}>
                <TextInput
                  style={[styles.input, { flex: 1, backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
                  placeholder="domainanda.com"
                  placeholderTextColor={colors.textDim}
                  value={domain}
                  onChangeText={(t) => {
                    setDomain(t);
                    setCheckResult(null);
                  }}
                  autoCapitalize="none"
                />
                <TouchableOpacity
                  style={[styles.checkBtn, { backgroundColor: colors.primary }]}
                  onPress={handleCheckDomain}
                  disabled={isChecking}
                >
                  {isChecking ? (
                    <ActivityIndicator color="#fff" size="small" />
                  ) : (
                    <Text style={styles.checkBtnText}>Periksa</Text>
                  )}
                </TouchableOpacity>
              </View>

              {checkResult && checkResult.available && (
                <View style={[styles.availableBanner, { backgroundColor: colors.primaryLight }]}>
                  <Ionicons name="checkmark-circle" size={20} color={colors.primary} />
                  <Text style={[styles.availableText, { color: colors.primary }]}>
                    Domain @{domain} tersedia untuk didaftarkan!
                  </Text>
                </View>
              )}
            </View>

            {/* Registration Form when checked */}
            {checkResult && checkResult.available && (
              <View style={[styles.card, { backgroundColor: colors.card, borderColor: colors.cardBorder, marginTop: 16 }]}>
                <Text style={[styles.cardTitle, { color: colors.text }]}>Informasi Akun Administrator</Text>

                <Text style={[styles.label, { color: colors.textMuted, marginTop: 12 }]}>Akun Utama (Username)</Text>
                <View style={styles.inputWithSuffix}>
                  <TextInput
                    style={[styles.input, { flex: 1, backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
                    placeholder="admin"
                    placeholderTextColor={colors.textDim}
                    value={localPart}
                    onChangeText={setLocalPart}
                    autoCapitalize="none"
                  />
                  <Text style={[styles.inputSuffixText, { color: colors.primary }]}>@{domain}</Text>
                </View>

                <Text style={[styles.label, { color: colors.textMuted, marginTop: 12 }]}>Nama Pemilik / Brand</Text>
                <TextInput
                  style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
                  placeholder="Contoh: Budi Santoso"
                  placeholderTextColor={colors.textDim}
                  value={adminName}
                  onChangeText={setAdminName}
                />

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

                <TouchableOpacity
                  style={[styles.primaryBtn, { backgroundColor: colors.primary, marginTop: 20 }]}
                  onPress={handleRegister}
                  disabled={isRegistering}
                >
                  {isRegistering ? (
                    <ActivityIndicator color="#fff" />
                  ) : (
                    <Text style={styles.primaryBtnText}>Daftarkan Domain & Akun</Text>
                  )}
                </TouchableOpacity>
              </View>
            )}
          </View>
        )}
      </ScrollView>
    </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 },
  cardTitle: { fontSize: 16, fontWeight: "bold" },
  cardSub: { fontSize: 12, marginTop: 4, marginBottom: 16 },
  searchRow: { flexDirection: "row", gap: 10 },
  input: { borderWidth: 1, borderRadius: 10, paddingHorizontal: 14, paddingVertical: 12, fontSize: 14 },
  checkBtn: { borderRadius: 10, paddingHorizontal: 18, justifyContent: "center" },
  checkBtnText: { color: "#fff", fontWeight: "bold", fontSize: 13 },
  availableBanner: { flexDirection: "row", alignItems: "center", gap: 8, padding: 12, borderRadius: 10, marginTop: 14 },
  availableText: { fontSize: 13, fontWeight: "bold" },
  label: { fontSize: 12, fontWeight: "600", marginBottom: 6 },
  inputWithSuffix: { flexDirection: "row", alignItems: "center", gap: 8 },
  inputSuffixText: { fontSize: 14, fontWeight: "bold" },
  primaryBtn: { borderRadius: 12, paddingVertical: 14, alignItems: "center" },
  primaryBtnText: { color: "#fff", fontWeight: "bold", fontSize: 14 },
  successBanner: { flexDirection: "row", alignItems: "center", gap: 12, padding: 16, borderRadius: 16, borderWidth: 1, marginBottom: 16 },
  successTitle: { fontSize: 16, fontWeight: "bold" },
  successSub: { fontSize: 13, marginTop: 2 },
  recordHeader: { fontSize: 13, fontWeight: "700" },
  recordBox: { padding: 12, borderRadius: 10, marginTop: 6 },
  recordRow: { fontSize: 11, marginBottom: 4 },
  recordValue: { fontSize: 12, fontWeight: "bold", fontFamily: "monospace" },
});
