import React, { useContext, useEffect, useState } from "react";
import axios from "axios";
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  TextInput,
  ScrollView,
  StyleSheet,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import UserContext from "../../contexts/UserContext";
import * as ImagePicker from "expo-image-picker";
import NetInfo from "@react-native-community/netinfo";
import { useSQLiteContext } from "expo-sqlite";

const ProfileInitial = () => {
  const { user, setUser } = useContext(UserContext);
  const [profileImage, setProfileImage] = useState(null);
  const [userId, setUserId] = useState(null);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [church, setChurch] = useState("");
  const [isEditing, setIsEditing] = useState(false);
  const [isOnline, setIsOnline] = useState(true);
  const db = useSQLiteContext();

  useEffect(() => {
    const unsubscribe = NetInfo.addEventListener((state) => {
      setIsOnline(state.isConnected);
    });

    return () => unsubscribe();
  }, []);

  useEffect(() => {
    const fetchUserProfile = async () => {
      try {
        if (isOnline) {
          const userData = { user: user };
          const response = await axios.post(
            "https://kiamabackend.mathenoid.com/api/profile",
            userData
          );
          if (response.data.success) {
            const userData = response.data.user;
            updateProfileData(userData);
          }
        } else {
          const offlineData = await fetchOfflineProfile();
          if (offlineData) {
            updateProfileData(offlineData);
          }
        }
      } catch (error) {
        // if (isOnline) {
        //   console.error("Error fetching user profile:", error);
        // }
        // // When offline, we silently fail and rely on offline data
      }
    };

    fetchUserProfile();
  }, [user, isOnline]);

  const updateProfileData = (userData) => {
    setUserId(userData.id);
    setName(userData.name);
    setEmail(userData.email);
    setPhone(userData.phone);
    setChurch(userData.homechurch);
    if (isOnline && userData.profileImageUrl) {
      setProfileImage(
        "https://kiamabackend.mathenoid.com/" + userData.profileImageUrl
      );
    } else {
      setProfileImage(null);
    }
  };

  const fetchOfflineProfile = async () => {
    try {
      const result = await db.getFirstAsync(
        "SELECT * FROM colleagues WHERE name = ?",
        [user]
      );
      return result;
    } catch (error) {
      console.error("Error fetching offline profile:", error);
      return null;
    }
  };

  const pickImage = async () => {
    if (!isOnline) {
      return; // Prevent image picking when offline
    }
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [1, 1],
      quality: 1,
    });

    if (!result.canceled) {
      setProfileImage(result.assets[0].uri);
    }
  };

  const handleUpdate = async () => {
    if (!isOnline) {
      return;
    }

    if (isEditing) {
      try {
        const formData = new FormData();
        formData.append("name", name);
        formData.append("email", email);
        formData.append("phone", phone);
        formData.append("homechurch", church);

        if (profileImage && !profileImage.startsWith("http")) {
          formData.append("profileImage", {
            uri: profileImage,
            type: "image/jpeg",
            name: "profile.jpg",
          });
        }

        const response = await axios.put(
          `https://kiamabackend.mathenoid.com/api/profile/${userId}`,
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          }
        );

        if (response.data.success) {
          setIsEditing(false);

          if (name !== user) {
            setUser(name);
          }
        }
      } catch (error) {
        console.error("Error updating profile:", error);
      }
    } else {
      setIsEditing(true);
    }
  };

  return (
    <SafeAreaView style={styles.container} edges={["bottom"]}>
      <ScrollView
        contentContainerStyle={styles.scrollView}
        showsVerticalScrollIndicator={false}
      >
        {!isOnline && (
          <View style={styles.offlineNotification}>
            <Text style={styles.offlineText}>
              Offline Mode - Connect to the internet to update your profile.
            </Text>
          </View>
        )}
        <View style={styles.mainProfileDiv}>
          <View style={styles.firstDiv}>
            <View style={styles.dp}>
              <Image
                source={{
                  uri:
                    isOnline && profileImage
                      ? profileImage
                      : "https://via.placeholder.com/150",
                }}
                style={styles.profileImage}
              />
              <Text style={styles.nameLabel}>{name}</Text>
            </View>
          </View>
          <View style={styles.verticalLine} />
          <View style={styles.secondDiv}>
            <FormInput
              label="Name"
              value={name}
              onChangeText={setName}
              editable={isOnline && isEditing}
            />
            <FormInput
              label="Email"
              value={email}
              onChangeText={setEmail}
              editable={isOnline && isEditing}
            />
            <FormInput
              label="Phone Number"
              value={phone}
              onChangeText={setPhone}
              editable={isOnline && isEditing}
            />
            <FormInput
              label="Home Church"
              value={church}
              onChangeText={setChurch}
              editable={isOnline && isEditing}
            />
          </View>
        </View>
        {isOnline && (
          <View style={styles.lowerUpdateDiv}>
            <TouchableOpacity
              style={styles.updateButton}
              onPress={handleUpdate}
            >
              <Text style={styles.updateButtonText}>
                {isEditing ? "Save Update" : "Update"}
              </Text>
            </TouchableOpacity>
          </View>
        )}
      </ScrollView>
    </SafeAreaView>
  );
};

const FormInput = ({ label, value, onChangeText, editable }) => (
  <View style={styles.formGroup}>
    <Text style={styles.label}>{label}</Text>
    <TextInput
      style={[styles.input, !editable && styles.readonlyInput]}
      value={value}
      onChangeText={onChangeText}
      editable={editable}
    />
  </View>
);

const styles = StyleSheet.create({
  offlineNotification: {
    backgroundColor: "#f57c00",
    padding: 10,
    marginBottom: 10,
    borderRadius: 5,
  },
  offlineText: {
    color: "#fff",
    textAlign: "center",
  },
  container: {
    flex: 1,
    backgroundColor: "#f5f5f5",
    marginBottom: 20,
  },
  scrollView: {
    paddingTop: 10,
    paddingHorizontal: 16,
  },
  mainProfileDiv: {
    backgroundColor: "white",
    borderRadius: 8,
    padding: 16,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  firstDiv: {
    alignItems: "center",
    marginBottom: 20,
  },
  dp: {
    alignItems: "center",
    marginBottom: 16,
  },
  profileImage: {
    width: 150,
    height: 150,
    borderRadius: 75,
  },
  nameLabel: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: "bold",
  },
  verticalLine: {
    height: 1,
    backgroundColor: "#e0e0e0",
    marginVertical: 16,
  },
  secondDiv: {
    marginBottom: 16,
  },
  formGroup: {
    marginBottom: 16,
  },
  label: {
    fontSize: 14,
    marginBottom: 4,
    color: "#333",
  },
  input: {
    borderWidth: 1,
    borderColor: "#ced4da",
    borderRadius: 4,
    padding: 8,
    fontSize: 16,
  },
  readonlyInput: {
    backgroundColor: "#f0f0f0",
  },
  lowerUpdateDiv: {
    alignItems: "center",
    marginTop: 16,
  },
  updateButton: {
    backgroundColor: "#28a745",
    paddingVertical: 12,
    paddingHorizontal: 24,
    borderRadius: 4,
  },
  updateButtonText: {
    color: "white",
    fontSize: 16,
    fontWeight: "bold",
  },
});

export default ProfileInitial;
