import React, { useState } from "react";
import { View, StyleSheet, ScrollView, Alert } from "react-native";
import {
  TextInput,
  Button,
  Card,
  Text,
  Title,
  Paragraph,
} from "react-native-paper";
import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router";
import { LinearGradient } from "expo-linear-gradient";

const ForgotPassword = () => {
  const [step, setStep] = useState(1);
  const [phone, setPhone] = useState("");
  const [homeChurch, setHomeChurch] = useState("");
  const [newPassword, setNewPassword] = useState("");

  const handleForgotPasswordFinished = () => {
    router.push("/");
  };

  const handleSubmit = async () => {
    if (step === 1) {
      try {
        const response = await fetch(
          "https://kiamabackend.mathenoid.com/api/forgot-password/verify",
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ phone, homeChurch }),
          }
        );
        const data = await response.json();
        if (data.success) {
          setStep(2);
        } else {
          Alert.alert(
            "Error",
            "No member found with the provided information."
          );
        }
      } catch (error) {
        Alert.alert("Error", "An error occurred. Please try again.");
      }
    } else {
      try {
        const response = await fetch(
          "https://kiamabackend.mathenoid.com/api/forgot-password/reset",
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ phone, homeChurch, newPassword }),
          }
        );
        const data = await response.json();
        if (data.success) {
          handleForgotPasswordFinished();
          Alert.alert("Success", "Password updated successfully!");
        } else {
          Alert.alert("Error", "Failed to update password. Please try again.");
        }
      } catch (error) {
        Alert.alert("Error", "An error occurred. Please try again.");
      }
    }
  };

  return (
    <ScrollView contentContainerStyle={styles.container}>
      <LinearGradient colors={["#e8f5e9", "#c8e6c9"]} style={styles.gradient}>
        <Card style={styles.card}>
          <Card.Content>
            <Title style={styles.headerText}>Forgot Password</Title>
            <Paragraph style={styles.subText}>
              {step === 1
                ? "Please enter your phone number and home church to verify your account."
                : "Enter your new password to reset your account."}
            </Paragraph>
            <View style={styles.form}>
              {step === 1 ? (
                <>
                  <TextInput
                    left={<TextInput.Icon icon="phone" color="#66bb6a" />}
                    style={styles.input}
                    mode="outlined"
                    label="Phone Number"
                    value={phone}
                    onChangeText={setPhone}
                    keyboardType="phone-pad"
                    theme={{ colors: { primary: "#66bb6a" } }}
                  />
                  <TextInput
                    left={<TextInput.Icon icon="home" color="#66bb6a" />}
                    style={styles.input}
                    mode="outlined"
                    label="Home Church"
                    value={homeChurch}
                    onChangeText={setHomeChurch}
                    theme={{ colors: { primary: "#66bb6a" } }}
                  />
                </>
              ) : (
                <TextInput
                  left={<TextInput.Icon icon="lock" color="#66bb6a" />}
                  style={styles.input}
                  mode="outlined"
                  label="New Password"
                  value={newPassword}
                  onChangeText={setNewPassword}
                  secureTextEntry
                  theme={{ colors: { primary: "#66bb6a" } }}
                />
              )}
              <Button
                mode="contained"
                onPress={handleSubmit}
                style={styles.button}
                labelStyle={styles.buttonText}
                icon={({ size, color }) => (
                  <Ionicons name="send" size={size} color={color} />
                )}
              >
                {step === 1 ? "Verify" : "Reset Password"}
              </Button>
            </View>
          </Card.Content>
        </Card>
      </LinearGradient>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flexGrow: 1,
  },
  gradient: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    padding: 20,
  },
  card: {
    width: "100%",
    maxWidth: 400,
    borderRadius: 15,
    elevation: 5,
    backgroundColor: "#ffffff",
  },
  headerText: {
    fontSize: 28,
    fontFamily: "outfit-medium",
    color: "#2e7d32",
    textAlign: "center",
    marginBottom: 10,
    paddingTop: 10,
  },
  subText: {
    textAlign: "center",
    marginBottom: 20,
    color: "#333", //"#4caf50",
    fontFamily: "outfit",
  },
  form: {
    width: "100%",
  },
  input: {
    marginBottom: 15,
    backgroundColor: "#ffffff",
    fontFamily: "outfit",
  },
  button: {
    marginTop: 10,
    paddingVertical: 8,
    backgroundColor: "#66bb6a",

    borderRadius: 25,
  },
  buttonText: {
    fontSize: 18,
    fontFamily: "outfit",
  },
});

export default ForgotPassword;
