import React, { useState, useEffect } from "react";
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  Alert,
  ScrollView,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useNavigation, useRoute } from "@react-navigation/native";
import MapView, { Marker } from "react-native-maps";
import { Picker } from "@react-native-picker/picker";

const EditTPS = () => {
  const navigation = useNavigation();
  const route = useRoute();
  const { tps } = route.params || {}; // Handle missing tps object gracefully

  useEffect(() => {
    if (tps) {
      console.log("Received tps data:", tps);
    } else {
      console.log("No tps data received");
    }
  }, [tps]);

  const [nama, setNama] = useState(tps?.nama || "");
  const [kecamatan, setKecamatan] = useState(tps?.kecamatan || "");
  const [alamat, setAlamat] = useState(tps?.alamat || "");
  const [jenis, setJenis] = useState(tps?.jenis || "");
  const [luas, setLuas] = useState(tps?.luas || "");
  const [volume, setVolume] = useState(tps?.volume || "");
  const [latitude, setLatitude] = useState(tps?.latitude?.toString() || "");
  const [longitude, setLongitude] = useState(tps?.longitude?.toString() || "");

  const handleSave = () => {
    if (
      !nama ||
      !kecamatan ||
      !alamat ||
      !jenis ||
      !luas ||
      !volume ||
      !latitude ||
      !longitude
    ) {
      Alert.alert("Error", "Semua field harus diisi!");
      return;
    }

    const updatedTPS = {
      ...tps,
      nama,
      kecamatan,
      alamat,
      jenis,
      luas,
      volume,
      latitude: parseFloat(latitude),
      longitude: parseFloat(longitude),
    };

    // Here you can update your database or state with the updated data.
    navigation.goBack();
    Alert.alert("Sukses", "TPS berhasil diperbarui!");
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity
          style={styles.backButton}
          onPress={() => navigation.goBack()}
        >
          <Ionicons name="arrow-back" size={28} color="#000" />
        </TouchableOpacity>
        <Text style={styles.title}>EDIT LOKASI TPS</Text>
      </View>

      <ScrollView style={styles.formContainer}>
        <TextInput
          style={styles.input}
          placeholder="Nama TPS"
          value={nama}
          onChangeText={setNama}
        />
        <TextInput
          style={styles.input}
          placeholder="Luas TPS (m2)"
          value={luas}
          keyboardType="numeric"
          onChangeText={setLuas}
        />
        <TextInput
          style={styles.input}
          placeholder="Volume (m³)"
          value={volume}
          keyboardType="numeric"
          onChangeText={setVolume}
        />

        <Text style={styles.label}>Pilih Jenis TPS</Text>
        <Picker
          selectedValue={jenis}
          style={styles.picker}
          onValueChange={(itemValue) => setJenis(itemValue)}
        >
          <Picker.Item label="Container" value="Container" />
          <Picker.Item label="Depo Kecil" value="Depo Kecil" />
        </Picker>

        <TextInput
          style={styles.input}
          placeholder="Alamat"
          value={alamat}
          onChangeText={setAlamat}
        />

        <Text style={styles.label}>Pilih Kecamatan</Text>
        <Picker
          selectedValue={kecamatan}
          style={styles.picker}
          onValueChange={(itemValue) => setKecamatan(itemValue)}
        >
          <Picker.Item label="Nganjuk" value="Nganjuk" />
          <Picker.Item label="Bagor" value="Bagor" />
          <Picker.Item label="Wilangan" value="Wilangan" />
          <Picker.Item label="Baron" value="Baron" />
        </Picker>

        <TextInput
          style={styles.input}
          placeholder="Latitude"
          value={latitude}
          keyboardType="numeric"
          onChangeText={setLatitude}
        />
        <TextInput
          style={styles.input}
          placeholder="Longitude"
          value={longitude}
          keyboardType="numeric"
          onChangeText={setLongitude}
        />

        {/* MapView to show location */}
        {latitude && longitude ? (
          <MapView
            style={styles.map}
            initialRegion={{
              latitude: parseFloat(latitude),
              longitude: parseFloat(longitude),
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            }}
          >
            <Marker
              coordinate={{
                latitude: parseFloat(latitude),
                longitude: parseFloat(longitude),
              }}
            />
          </MapView>
        ) : null}

        <TouchableOpacity style={styles.saveButton} onPress={handleSave}>
          <Text style={styles.saveButtonText}>SIMPAN</Text>
        </TouchableOpacity>
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    padding: 16,
    marginTop: 30,
  },
  header: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 20,
  },
  backButton: {
    marginRight: 20,
  },
  title: {
    fontSize: 20,
    fontWeight: "bold",
    color: "#000",
  },
  formContainer: {
    marginTop: -15,
    padding: 15,
  },
  input: {
    borderWidth: 1,
    borderColor: "#ccc",
    borderRadius: 8,
    padding: 15,
    marginBottom: 12,
    fontSize: 14,
  },
  label: {
    fontSize: 14,
    fontWeight: "bold",
    marginBottom: 5,
  },
  picker: {
    height: 50,
    borderWidth: 1,
    borderColor: "#ccc",
    borderRadius: 8,
    marginBottom: 12,
  },
  map: {
    height: 200,
    marginBottom: 20,
  },
  saveButton: {
    width: "100%",
    padding: 15,
    backgroundColor: "#2D572C",
    alignItems: "center",
    borderRadius: 15,
  },
  saveButtonText: {
    color: "#fff",
    fontSize: 16,
    fontWeight: "bold",
  },
});

export default EditTPS;
