import React, { useState } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  Image,
  StyleSheet,
  Alert,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useNavigation } from "@react-navigation/native";
import * as ImagePicker from "expo-image-picker"; // Mengimpor expo-image-picker

const EditProfilScreen = () => {
  const navigation = useNavigation();

  // State untuk data profil
  const [userProfile, setUserProfile] = useState({
    name: "Johan Okta Pangestu",
    email: "okta@gmail.com",
    phone: "08123456789",
    address: "Jl. Raya No. 123, Nganjuk",
    photo:
      "https://i.ytimg.com/vi/b1XXKeq5ccQ/oar2.jpg?sqp=-oaymwEkCJUDENAFSFqQAgHyq4qpAxMIARUAAAAAJQAAyEI9AICiQ3gB&rs=AOn4CLBxYjkvH5GuWS8_SYMNsg5aIGYIRA", // Default photo
  });

  // Fungsi untuk memilih foto
  const handleChoosePhoto = async () => {
    // Meminta izin untuk mengakses galeri
    const permissionResult =
      await ImagePicker.requestMediaLibraryPermissionsAsync();

    if (permissionResult.granted === false) {
      alert("Izin akses galeri ditolak!");
      return;
    }

    // Meluncurkan galeri untuk memilih gambar
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images, // Hanya gambar
      quality: 0.5, // Kualitas gambar
    });

    if (!result.canceled) {
      // Update foto profil dengan gambar yang dipilih
      setUserProfile({ ...userProfile, photo: result.uri });
    }
  };

  // Fungsi untuk menghapus foto
  const handleRemovePhoto = () => {
    Alert.alert(
      "Konfirmasi",
      "Apakah Anda yakin ingin menghapus foto profil?",
      [
        { text: "Batal", style: "cancel" },
        {
          text: "Hapus",
          onPress: () => setUserProfile({ ...userProfile, photo: "" }), // Hapus foto profil
        },
      ]
    );
  };

  // Fungsi untuk menyimpan perubahan profil
  const handleSaveChanges = () => {
    // Tampilkan alert sebagai konfirmasi
    Alert.alert("Profil Diperbarui", "Perubahan profil berhasil disimpan.");
    // Logika untuk menyimpan perubahan, misalnya API request, bisa ditambahkan di sini.
    console.log(userProfile);
  };

  return (
    <View style={styles.container}>
      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <Ionicons name="arrow-back" size={24} color="#000" />
        </TouchableOpacity>
        <Text style={styles.headerText}>EDIT PROFIL</Text>
      </View>

      {/* Foto Profil */}
      <View style={styles.profileImageContainer}>
        {userProfile.photo ? (
          <Image
            source={{ uri: userProfile.photo }}
            style={styles.profileImage}
          />
        ) : (
          <View style={styles.defaultImage}>
            <Ionicons name="person-circle-outline" size={100} color="#2C6B2F" />
          </View>
        )}

        <TouchableOpacity
          style={styles.changePhotoButton}
          onPress={handleChoosePhoto}
        >
          <Text style={styles.changePhotoButtonText}>Ubah Foto Profil</Text>
        </TouchableOpacity>

        {userProfile.photo && (
          <TouchableOpacity
            style={styles.removePhotoButton}
            onPress={handleRemovePhoto}
          >
            <Text style={styles.removePhotoButtonText}>Hapus Foto Profil</Text>
          </TouchableOpacity>
        )}
      </View>

      {/* Form Edit Profil */}
      <View style={styles.form}>
        <Text style={styles.label}>Nama:</Text>
        <TextInput
          style={styles.input}
          value={userProfile.name}
          onChangeText={(text) =>
            setUserProfile({ ...userProfile, name: text })
          }
        />

        <Text style={styles.label}>Email:</Text>
        <TextInput
          style={styles.input}
          value={userProfile.email}
          onChangeText={(text) =>
            setUserProfile({ ...userProfile, email: text })
          }
        />

        <Text style={styles.label}>No. HP:</Text>
        <TextInput
          style={styles.input}
          value={userProfile.phone}
          onChangeText={(text) =>
            setUserProfile({ ...userProfile, phone: text })
          }
        />

        <Text style={styles.label}>Alamat:</Text>
        <TextInput
          style={styles.input}
          value={userProfile.address}
          onChangeText={(text) =>
            setUserProfile({ ...userProfile, address: text })
          }
        />
      </View>

      {/* Tombol Simpan */}
      <TouchableOpacity
        style={styles.saveButton}
        onPress={() => navigation.navigate("ProfilAdminScreen")}
      >
        <Text style={styles.saveButtonText}>Simpan</Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    padding: 20,
  },
  header: {
    marginTop: 40,
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 20,
  },
  headerText: {
    fontSize: 20,
    fontWeight: "bold",
    color: "#000",
    marginLeft: 10,
  },
  profileImageContainer: {
    alignItems: "center",
    marginBottom: 20,
  },
  profileImage: {
    width: 150,
    height: 150,
    borderRadius: 75,
    marginBottom: 10,
  },
  defaultImage: {
    width: 150,
    height: 150,
    borderRadius: 75,
    backgroundColor: "#ddd",
    justifyContent: "center",
    alignItems: "center",
  },
  changePhotoButton: {
    backgroundColor: "#ddd",
    paddingVertical: 8,
    borderRadius: 8,
    marginBottom: 10,
    width: "30%",
    alignItems: "center",
    borderWidth: 0.5,
  },
  changePhotoButtonText: {
    color: "#000",
    fontWeight: "bold",
  },
  removePhotoButton: {
    backgroundColor: "#E74C3C",
    paddingVertical: 8,
    borderRadius: 8,
    width: "30%",
    alignItems: "center",
    borderWidth: 0.5,
  },
  removePhotoButtonText: {
    color: "#fff",
    fontWeight: "bold",
  },
  form: {
    marginBottom: 20,
  },
  label: {
    fontSize: 14,
    fontWeight: "bold",
    color: "#555",
    marginBottom: 5,
  },
  input: {
    borderWidth: 1,
    borderColor: "#ccc",
    borderRadius: 5,
    padding: 10,
    marginBottom: 20,
    fontSize: 16,
    color: "#333",
  },
  saveButton: {
    backgroundColor: "#2D572C",
    paddingVertical: 12,
    borderRadius: 8,
    alignItems: "center",
  },
  saveButtonText: {
    fontSize: 16,
    color: "#fff",
    fontWeight: "bold",
  },
});

export default EditProfilScreen;
