import React, { useState } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  Image,
  ScrollView,
  StyleSheet,
  Alert,
} from "react-native";
import * as ImagePicker from "expo-image-picker"; // import image picker
import { Ionicons } from "@expo/vector-icons";
import { useNavigation } from "@react-navigation/native";
const DaftarBarang = () => {
  const navigation = useNavigation();
  const [items, setItems] = useState([
    {
      id: 1,
      name: "Botol Minum",
      coin: 300,
      image: require("../../assets/images/botol1.png"),
    },
    {
      id: 2,
      name: "Botol Minum Anak",
      coin: 350,
      image: require("../../assets/images/botol2.png"),
    },
  ]);

  const [isEditing, setIsEditing] = useState(false);
  const [formItem, setFormItem] = useState({
    id: null,
    name: "",
    coin: "",
    image: null,
  });

  const pickImage = async () => {
    // Minta izin akses galeri
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== "granted") {
      Alert.alert(
        "Izin Ditolak",
        "Izin akses galeri dibutuhkan untuk memilih foto"
      );
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      quality: 1,
    });

    if (!result.canceled) {
      setFormItem({ ...formItem, image: { uri: result.assets[0].uri } });
    }
  };

  const handleEdit = (item) => {
    setFormItem(item);
    setIsEditing(true);
  };

  const handleAddItem = () => {
    setFormItem({ id: null, name: "", coin: "", image: null });
    setIsEditing(true);
  };

  const handleSubmit = () => {
    if (formItem.name === "" || formItem.coin === "") {
      Alert.alert("Error", "Nama dan koin wajib diisi");
      return;
    }

    if (formItem.id) {
      // Edit
      setItems(items.map((i) => (i.id === formItem.id ? { ...formItem } : i)));
    } else {
      // Tambah
      setItems([
        ...items,
        {
          ...formItem,
          id: Date.now(),
          image: formItem.image
            ? formItem.image
            : require("../../assets/images/botol1.png"),
        },
      ]);
    }
    setIsEditing(false);
  };

  const handleDelete = (id) => {
    Alert.alert("Konfirmasi", "Apakah Anda yakin ingin menghapus item ini?", [
      {
        text: "Batal",
        style: "cancel",
      },
      {
        text: "Hapus",
        style: "destructive",
        onPress: () => {
          setItems(items.filter((item) => item.id !== id));
        },
      },
    ]);
  };

  return (
    <View style={styles.container}>
      <View style={styles.headerRow}>
        <TouchableOpacity
          style={styles.backButton}
          onPress={() => navigation.navigate("TukarKoin")}
        >
          <Ionicons name="arrow-back" size={28} color="#000" />
        </TouchableOpacity>
        <Text style={styles.title}>DAFTAR BARANG</Text>
      </View>
      <TouchableOpacity style={styles.addButton} onPress={handleAddItem}>
        <Text style={styles.addButtonText}>+ Tambah Item</Text>
      </TouchableOpacity>

      {isEditing && (
        <View style={styles.form}>
          <TextInput
            placeholder="Nama Barang"
            value={formItem.name}
            onChangeText={(text) => setFormItem({ ...formItem, name: text })}
            style={styles.input}
          />
          <TextInput
            placeholder="Jumlah Koin"
            keyboardType="numeric"
            value={formItem.coin.toString()}
            onChangeText={(text) => setFormItem({ ...formItem, coin: text })}
            style={styles.input}
          />

          {/* Tombol pilih foto */}
          <TouchableOpacity style={styles.imagePickerBtn} onPress={pickImage}>
            <Text style={styles.imagePickerText}>
              {formItem.image ? "Ganti Foto" : "Pilih Foto"}
            </Text>
          </TouchableOpacity>

          {/* Preview foto yang dipilih */}
          {formItem.image && (
            <Image source={formItem.image} style={styles.previewImage} />
          )}

          <TouchableOpacity style={styles.submitBtn} onPress={handleSubmit}>
            <Text style={styles.submitText}>
              {formItem.id ? "Simpan Perubahan" : "Tambah"}
            </Text>
          </TouchableOpacity>
        </View>
      )}

      <ScrollView showsVerticalScrollIndicator={false}>
        <View style={styles.itemGrid}>
          {items.map((item) => (
            <View key={item.id} style={styles.itemCard}>
              <Image source={item.image} style={styles.itemImage} />
              <Text style={styles.itemName}>{item.name}</Text>
              <View style={styles.coinBoxItem}>
                <Text style={styles.itemCoin}>{item.coin} Koin</Text>
              </View>
              <View style={styles.actionRow}>
                <TouchableOpacity
                  style={styles.editBtn}
                  onPress={() => handleEdit(item)}
                >
                  <Text style={styles.actionText}>Edit</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.deleteBtn}
                  onPress={() => handleDelete(item.id)}
                >
                  <Text style={styles.actionText}>Hapus</Text>
                </TouchableOpacity>
              </View>
            </View>
          ))}
        </View>
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, backgroundColor: "#fff" },
  backButton: { marginBottom: 10 },
  title: {
    fontSize: 22,
    fontWeight: "bold",
    color: "#000",
    textAlign: "left",
    marginBottom: 12,
    marginLeft: 20,
    marginRight: 50,
  },
  headerRow: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 16,
    marginTop: 30,
  },

  backButton: {
    marginRight: 10,
  },

  title: {
    fontSize: 22,
    fontWeight: "bold",
    color: "#000",
  },

  //   title: {
  //     fontSize: 26,
  //     fontWeight: "bold",
  //     color: "#000",
  //     marginBottom: 20,
  //     textAlign: "center",
  //     marginTop: 30,
  //   },
  addButton: {
    backgroundColor: "#2D572C",
    paddingVertical: 12,
    paddingHorizontal: 20,
    borderRadius: 10,
    alignSelf: "center",
    marginBottom: 20,
  },
  addButtonText: { color: "white", fontWeight: "bold", fontSize: 16 },
  form: {
    backgroundColor: "#f9f9f9",
    padding: 20,
    borderRadius: 12,
    marginBottom: 25,
    borderWidth: 1,
    borderColor: "#d1d1d1",
  },
  input: {
    backgroundColor: "#fff",
    padding: 14,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: "#ccc",
    marginBottom: 15,
    fontSize: 16,
  },
  imagePickerBtn: {
    backgroundColor: "#DDD",
    paddingVertical: 12,
    borderRadius: 8,
    alignItems: "center",
    marginBottom: 10,
    padding: 10,
    width: "40%",
  },
  imagePickerText: {
    color: "BLACK",
    fontWeight: "bold",
    fontSize: 16,
  },
  previewImage: {
    width: 100,
    height: 140,
    alignSelf: "center",
    marginBottom: 15,
    resizeMode: "contain",
    borderRadius: 10,
  },
  submitBtn: {
    backgroundColor: "#2D572C",
    paddingVertical: 14,
    borderRadius: 8,
    alignItems: "center",
  },
  submitText: { color: "white", fontWeight: "bold", fontSize: 16 },
  itemGrid: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "space-between",
  },
  itemCard: {
    width: "48%",
    backgroundColor: "#fff",
    borderRadius: 12,
    padding: 15,
    marginBottom: 20,
    elevation: 4,
    shadowColor: "#000",
    shadowOpacity: 0.1,
    shadowRadius: 6,
    shadowOffset: { width: 0, height: 3 },
    alignItems: "center",
  },
  itemImage: {
    width: 80,
    height: 110,
    resizeMode: "contain",
    marginBottom: 12,
  },
  itemName: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#2D572C",
    marginBottom: 8,
    textAlign: "center",
  },
  coinBoxItem: {
    backgroundColor: "#2D572C",
    paddingVertical: 6,
    paddingHorizontal: 16,
    borderRadius: 8,
    marginBottom: 10,
  },
  itemCoin: {
    color: "white",
    fontWeight: "bold",
    fontSize: 16,
  },
  actionRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    width: "100%",
  },
  editBtn: {
    flex: 1,
    backgroundColor: "#4CAF50",
    paddingVertical: 10,
    borderRadius: 8,
    alignItems: "center",
    marginRight: 8,
  },
  deleteBtn: {
    flex: 1,
    backgroundColor: "#E53935",
    paddingVertical: 10,
    borderRadius: 8,
    alignItems: "center",
  },
  actionText: { color: "white", fontWeight: "bold", fontSize: 14 },
});

export default DaftarBarang;
