import React, { useState } from "react";
import {
  View,
  Text,
  Modal,
  TouchableOpacity,
  StyleSheet,
  ActivityIndicator,
  Alert,
  Linking,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useTheme } from "../context/ThemeContext";

export default function UpdateModal({ visible, updateInfo, onClose }) {
  const { colors } = useTheme();
  const [isUpdating, setIsUpdating] = useState(false);

  if (!updateInfo || !updateInfo.updateAvailable) return null;

  const handleStartUpdate = async () => {
    setIsUpdating(true);
    try {
      if (updateInfo.apkUrl) {
        await Linking.openURL(updateInfo.apkUrl);
      } else {
        Alert.alert("Sukses", "Aplikasi berhasil disinkronkan ke versi terbaru!");
      }
      onClose();
    } catch (e) {
      Alert.alert("Gagal", "Tidak dapat membuka tautan unduhan.");
    } finally {
      setIsUpdating(false);
    }
  };

  return (
    <Modal visible={visible} transparent animationType="fade">
      <View style={styles.overlay}>
        <View style={[styles.dialog, { backgroundColor: colors.card, borderColor: colors.cardBorder }]}>
          <View style={[styles.iconCircle, { backgroundColor: colors.primaryLight }]}>
            <Ionicons name="cloud-download-outline" size={32} color={colors.primary} />
          </View>

          <Text style={[styles.title, { color: colors.text }]}>Pembaruan Tersedia!</Text>
          <Text style={[styles.versionPill, { color: colors.primary, backgroundColor: colors.primaryLight }]}>
            Versi {updateInfo.latestVersion} (Saat ini: v{updateInfo.currentVersion})
          </Text>

          <Text style={[styles.changelogTitle, { color: colors.textMuted }]}>
            Apa yang Baru:
          </Text>

          <View style={styles.changelogBox}>
            {updateInfo.changelog.map((item, idx) => (
              <View key={idx} style={styles.bulletRow}>
                <Ionicons name="checkmark-circle" size={16} color={colors.primary} style={{ marginTop: 2 }} />
                <Text style={[styles.bulletText, { color: colors.text }]}>{item}</Text>
              </View>
            ))}
          </View>

          <View style={styles.btnRow}>
            <TouchableOpacity
              onPress={onClose}
              style={[styles.btn, { backgroundColor: colors.subCard }]}
            >
              <Text style={[styles.btnText, { color: colors.textMuted }]}>Nanti Saja</Text>
            </TouchableOpacity>

            <TouchableOpacity
              onPress={handleStartUpdate}
              disabled={isUpdating}
              style={[styles.btn, { backgroundColor: colors.primary }]}
            >
              {isUpdating ? (
                <ActivityIndicator color="#fff" size="small" />
              ) : (
                <Text style={[styles.btnText, { color: "#fff" }]}>Perbarui Sekarang</Text>
              )}
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  overlay: { flex: 1, backgroundColor: "rgba(0,0,0,0.7)", justifyContent: "center", padding: 24 },
  dialog: { borderRadius: 20, padding: 22, borderWidth: 1, alignItems: "center" },
  iconCircle: { width: 64, height: 64, borderRadius: 32, alignItems: "center", justifyContent: "center", marginBottom: 14 },
  title: { fontSize: 18, fontWeight: "800", marginBottom: 6 },
  versionPill: { paddingHorizontal: 12, paddingVertical: 4, borderRadius: 12, fontSize: 12, fontWeight: "bold", marginBottom: 14 },
  changelogTitle: { fontSize: 12, fontWeight: "700", alignSelf: "flex-start", marginBottom: 8 },
  changelogBox: { alignSelf: "stretch", marginBottom: 20, gap: 6 },
  bulletRow: { flexDirection: "row", gap: 8, alignItems: "flex-start" },
  bulletText: { fontSize: 13, flex: 1, lineHeight: 18 },
  btnRow: { flexDirection: "row", gap: 10, alignSelf: "stretch" },
  btn: { flex: 1, paddingVertical: 12, borderRadius: 12, alignItems: "center" },
  btnText: { fontWeight: "700", fontSize: 13 },
});
