import React, { useState } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  StyleSheet,
  Image,
  FlatList,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useNavigation } from "@react-navigation/native";
import * as Location from "expo-location";
import * as ImagePicker from "expo-image-picker";
import { Picker } from "@react-native-picker/picker"; // Import Picker

const desaOptions = ["Cangkringan", "Bogo", "Pesukidul", "Grojogan"];
const kecamatanOptions = ["Nganjuk", "Bagor", "Berbek", "Pace", "Wilangan"];

export default function PengaduanSampah() {
  const navigation = useNavigation();

  const [form, setForm] = useState({
    nama: "",
    noHp: "",
    tanggal: "",
    kategori: "",
    namaJalan: "",
    desa: "",
    kecamatan: "",
    tempat: "",
    catatan: "",
  });

  const [imageUris, setImageUris] = useState([]); // Using array for multiple images
  const [location, setLocation] = useState(null);
  const [filteredDesa, setFilteredDesa] = useState(desaOptions);

  const handleInputChange = (key, value) => {
    setForm({ ...form, [key]: value });
  };

  // Filter desa based on input
  const handleDesaSearch = (text) => {
    setForm({ ...form, desa: text });
    setFilteredDesa(
      desaOptions.filter((desa) =>
        desa.toLowerCase().includes(text.toLowerCase())
      )
    );
  };

  const getCurrentLocation = async () => {
    const { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== "granted") {
      alert("Izin lokasi ditolak");
      return;
    }

    try {
      // Get user location
      const loc = await Location.getCurrentPositionAsync({
        accuracy: Location.Accuracy.High,
      });
      setLocation(loc.coords);

      // Geocoding API
      const geocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${loc.coords.latitude},${loc.coords.longitude}&key=YOUR_GOOGLE_MAPS_API_KEY`;

      const response = await fetch(geocodeUrl);
      const data = await response.json();

      if (data.status === "OK" && data.results.length > 0) {
        const address = data.results[0].address_components;

        const street =
          address.find((component) => component.types.includes("route"))
            ?.long_name || "";
        const village =
          address.find((component) => component.types.includes("locality"))
            ?.long_name || "";
        const place =
          address.find((component) => component.types.includes("neighborhood"))
            ?.long_name || "";

        setForm((prevForm) => ({
          ...prevForm,
          namaJalan: street,
          desa: village,
          tempat: place,
        }));
      } else {
        alert("Tidak dapat menemukan alamat untuk lokasi ini.");
      }
    } catch (error) {
      console.error("Error getting address or location:", error);
      alert("Terjadi kesalahan saat mengambil alamat atau lokasi.");
    }
  };

  const pickImage = async () => {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== "granted") {
      alert("Sorry, we need camera roll permissions to make this work!");
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      quality: 1,
    });

    if (!result.canceled && result.assets.length > 0) {
      // Add new image URI to the imageUris array
      setImageUris((prevImages) => [...prevImages, result.assets[0].uri]);
    }
  };

  const handleSubmit = () => {
    // Cek semua field
    if (!form.nama || !form.noHp || !form.tempat) {
      alert("Harap lengkapi semua informasi yang diperlukan!");
      return;
    }

    // validasi
    console.log("Data Laporan:", { ...form, imageUris, location });
    // alert("Laporan berhasil dikirim!");
    navigation.navigate("PengaduanBerhasil");
  };

  return (
    <ScrollView contentContainerStyle={styles.container}>
      {/* Back Button */}
      <TouchableOpacity
        onPress={() => navigation.goBack()}
        style={styles.backButton}
      >
        <Ionicons name="arrow-back" size={24} color="#000" />
      </TouchableOpacity>
      <Text style={styles.title}>PENGADUAN SAMPAH</Text>
      <TextInput
        style={styles.input}
        placeholder="Nama Warga (Contoh: Johan Okta)"
        value={form.nama}
        onChangeText={(text) => handleInputChange("nama", text)}
      />
      <TextInput
        style={styles.input}
        placeholder="No. HP Warga (Contoh: 081234567890)"
        keyboardType="phone-pad"
        value={form.noHp}
        onChangeText={(text) => handleInputChange("noHp", text)}
      />
      <Text style={styles.section}>LOKASI KEJADIAN</Text>

      {/* Kecamatan Dropdown */}
      <Text style={styles.inputLabel}>Kecamatan</Text>
      <Picker
        selectedValue={form.kecamatan}
        onValueChange={(itemValue) => handleInputChange("kecamatan", itemValue)}
        style={styles.input}
      >
        {kecamatanOptions.map((kecamatan, index) => (
          <Picker.Item key={index} label={kecamatan} value={kecamatan} />
        ))}
      </Picker>

      <TextInput
        style={styles.input}
        placeholder="Tempat Kejadian (Contoh: Desa Cangkringan gang 4, Depan Toko)"
        value={form.tempat}
        onChangeText={(text) => handleInputChange("tempat", text)}
      />
      <TextInput
        style={[styles.input, { height: 100 }]}
        multiline
        placeholder="Catatan"
        value={form.catatan}
        onChangeText={(text) => handleInputChange("catatan", text)}
      />
      <Text style={styles.section}>BUKTI PENDUKUNG</Text>
      <View style={styles.row}>
        <TouchableOpacity style={styles.buttonUpload} onPress={pickImage}>
          <Text style={styles.buttonText}>Unggah</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={styles.buttonUpload}
          onPress={getCurrentLocation}
        >
          <Text style={styles.buttonText}>Lokasi Saat Ini</Text>
        </TouchableOpacity>
      </View>
      {/* Display uploaded images */}
      <ScrollView horizontal style={styles.imageGallery}>
        {imageUris.map((uri, index) => (
          <Image key={index} source={{ uri }} style={styles.imagePreview} />
        ))}
      </ScrollView>
      <TouchableOpacity style={styles.submitButton} onPress={handleSubmit}>
        <Text style={styles.submitText}>LAPORKAN</Text>
      </TouchableOpacity>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flexGrow: 1,
    padding: 30,
    backgroundColor: "#fff",
    paddingTop: 20,
    marginTop: 40,
  },
  backButton: {
    position: "absolute",
    top: 20,
    left: 20,
    zIndex: 10,
  },
  title: {
    fontWeight: "bold",
    fontSize: 22,
    marginBottom: 20,
    color: "#000",
    textAlign: "left",
    marginLeft: 25,
  },
  section: {
    marginTop: 20,
    fontWeight: "600",
    marginBottom: 10,
    color: "#444",
  },
  input: {
    borderWidth: 1,
    borderColor: "#aaa",
    padding: 10,
    borderRadius: 8,
    marginBottom: 15,
  },
  inputLabel: {
    fontWeight: "600",
    marginBottom: 5,
  },
  row: {
    flexDirection: "row",
    justifyContent: "space-between",
  },
  buttonUpload: {
    backgroundColor: "#ccc",
    padding: 10,
    borderRadius: 8,
    flex: 1,
    marginRight: 10,
  },
  buttonText: {
    textAlign: "center",
  },
  imagePreview: {
    marginTop: 10,
    width: 100,
    height: 100,
    borderRadius: 10,
    marginRight: 10,
  },
  imageGallery: {
    flexDirection: "row",
    marginTop: 10,
    marginBottom: 20,
  },
  submitButton: {
    marginTop: 30,
    backgroundColor: "#2f4f2f",
    padding: 15,
    borderRadius: 10,
  },
  submitText: {
    color: "#fff",
    textAlign: "center",
    fontWeight: "bold",
  },
});
