import React, { useState } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  Image,
  Alert,
} from "react-native";
import * as ImagePicker from "expo-image-picker";
import { LinearGradient } from "expo-linear-gradient";
import axios from "axios";
import { router } from "expo-router";

const SignupPage = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [church, setChurch] = useState("");
  const [phone, setPhone] = useState("");
  const [profileImage, setProfileImage] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [1, 1],
      quality: 1,
    });

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

  const checkExistingUser = async () => {
    try {
      const response = await axios.post(
        "https://kiamabackend.mathenoid.com/api/check-existing-user",
        {
          name: name.trim(),
          email: email.trim(),
          phone: phone.trim(),
          church: church.trim(),
        }
      );

      return response.data;
    } catch (error) {
      console.error("Error checking existing user:", error);
      throw error;
    }
  };

  const handleSignup = async () => {
    if (
      !name.trim() ||
      !email.trim() ||
      !password ||
      !church.trim() ||
      !phone.trim() ||
      !profileImage
    ) {
      Alert.alert("Error", "All fields are mandatory to sign up");
      return;
    }

    setIsLoading(true);
    try {
      // First, check if user exists
      const checkResult = await checkExistingUser();

      if (checkResult.exists) {
        let alertMessage = "";
        if (checkResult.type === "member") {
          alertMessage = "Please login instead.";
        } else if (checkResult.type === "applicant") {
          alertMessage = "Please wait for admin approval.";
        }

        Alert.alert(
          "Duplication error",
          `${checkResult.message}\n${alertMessage}`
        );

        // Clear all fields and navigate when user exists
        router.push("/");
        setName("");
        setEmail("");
        setPassword("");
        setChurch("");
        setPhone("");
        setProfileImage(null);
        return;
      }

      // If user doesn't exist, proceed with signup
      const formData = new FormData();
      formData.append("name", name.trim());
      formData.append("email", email.trim());
      formData.append("phone", phone.trim());
      formData.append("password", password);
      formData.append("church", church.trim());
      formData.append("profileImage", {
        uri: profileImage.uri,
        type: "image/jpeg",
        name: "profile.jpg",
      });

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

      if (response.data.success) {
        Alert.alert(
          "Success",
          "Successfully applied for membership, please await admin approval to access the system"
        );
        router.push("/");
        setName("");
        setEmail("");
        setPassword("");
        setChurch("");
        setPhone("");
        setProfileImage(null);
      } else {
        Alert.alert("Error", response.data.message || "Signup failed");
      }
    } catch (error) {
      Alert.alert(
        "Error",
        "An error occurred during signup. Please try again."
      );
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <LinearGradient colors={["#69c37b", "#fff"]} style={styles.container}>
      <View style={styles.formContainer}>
        <Text style={styles.title}>Join Our Community</Text>

        <TouchableOpacity
          style={styles.imagePickerContainer}
          onPress={pickImage}
          disabled={isLoading}
        >
          {profileImage ? (
            <Image
              source={{ uri: profileImage.uri }}
              style={styles.profileImage}
            />
          ) : (
            <View style={styles.placeholderImage}>
              <Text style={styles.placeholderText}>Add Profile Picture</Text>
            </View>
          )}
        </TouchableOpacity>

        <TextInput
          style={styles.input}
          placeholder="Name"
          value={name}
          onChangeText={setName}
          placeholderTextColor="#a0a0a0"
          editable={!isLoading}
        />
        <TextInput
          style={styles.input}
          placeholder="Email"
          value={email}
          onChangeText={setEmail}
          keyboardType="email-address"
          placeholderTextColor="#a0a0a0"
          editable={!isLoading}
        />
        <TextInput
          style={styles.input}
          placeholder="Password"
          value={password}
          onChangeText={setPassword}
          secureTextEntry
          placeholderTextColor="#a0a0a0"
          editable={!isLoading}
        />
        <TextInput
          style={styles.input}
          placeholder="Phone Number"
          value={phone}
          onChangeText={setPhone}
          keyboardType="phone-pad"
          placeholderTextColor="#a0a0a0"
          editable={!isLoading}
        />
        <TextInput
          style={styles.input}
          placeholder="Home Church"
          value={church}
          onChangeText={setChurch}
          placeholderTextColor="#a0a0a0"
          editable={!isLoading}
        />

        <TouchableOpacity
          style={[styles.button, isLoading && styles.buttonDisabled]}
          onPress={handleSignup}
          disabled={isLoading}
        >
          <Text style={styles.buttonText}>
            {isLoading ? "Processing..." : "Sign Up"}
          </Text>
        </TouchableOpacity>
      </View>
    </LinearGradient>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  formContainer: {
    width: "80%",
    backgroundColor: "rgba(255, 255, 255, 0.9)",
    borderRadius: 20,
    padding: 20,
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 4,
    },
    shadowOpacity: 0.3,
    shadowRadius: 4.65,
    elevation: 8,
  },
  title: {
    fontSize: 24,
    fontWeight: "bold",
    color: "#69c37b",
    marginBottom: 20,
  },
  imagePickerContainer: {
    marginBottom: 20,
  },
  profileImage: {
    width: 100,
    height: 100,
    borderRadius: 50,
  },
  placeholderImage: {
    width: 100,
    height: 100,
    borderRadius: 50,
    backgroundColor: "#e0e0e0",
    justifyContent: "center",
    alignItems: "center",
  },
  placeholderText: {
    color: "#69c37b",
  },
  input: {
    width: "100%",
    height: 50,
    backgroundColor: "#f0f0f0",
    borderRadius: 10,
    marginBottom: 15,
    paddingHorizontal: 15,
    fontSize: 16,
  },
  button: {
    width: "100%",
    height: 50,
    backgroundColor: "#69c37b",
    borderRadius: 10,
    justifyContent: "center",
    alignItems: "center",
  },
  buttonText: {
    color: "white",
    fontSize: 18,
    fontWeight: "bold",
  },
  buttonDisabled: {
    opacity: 0.7,
  },
});

export default SignupPage;
