import React, { useState, useContext } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  Image,
  ScrollView,
  Alert,
  ActivityIndicator,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import UserContext from "../contexts/UserContext";
import { useNavigation } from "expo-router";
import { LinearGradient } from "expo-linear-gradient";
import { useSQLiteContext } from "expo-sqlite";

const LoginForm = () => {
  const [showPassword, setShowPassword] = useState(false);
  const [formData, setFormData] = useState({
    username: "",
    password: "",
  });
  const [loading, setLoading] = useState(false);
  const { setUser, userRole } = useContext(UserContext);
  const db = useSQLiteContext();
  const navigation = useNavigation();

  const toggleShowPassword = () => {
    setShowPassword(!showPassword);
  };

  const changeHandler = (name, value) => {
    setFormData({ ...formData, [name]: value });
  };

  const validateForm = () => {
    if (!formData.username || !formData.password) {
      Alert.alert("Error", "Please enter both username and password");
      return false;
    }
    return true;
  };
  const storeDataInLocalDb = async (data) => {
    if (!db) {
      throw new Error("Database not initialized");
    }

    try {
      // Clear existing data
      await db.execAsync("DELETE FROM colleagues");
      await db.execAsync("DELETE FROM colleaguesApplied");
      await db.execAsync("DELETE FROM songs");

      // Insert new data
      await insertColleagues(db, data.colleagues);
      await insertColleaguesApplied(db, data.colleaguesApplied);
      await insertSongs(db, data.songs);

      console.log("Data successfully stored in local database");
    } catch (error) {
      console.error("Error storing data in local database:", error);
      throw error;
    }
  };

  const insertColleagues = async (db, colleagues) => {
    const insertQuery = `INSERT INTO colleagues
    (id, name, email, homechurch, password, profileImageUrl, phone, role)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;

    for (const colleague of colleagues) {
      try {
        await db.runAsync(insertQuery, [
          colleague.id,
          colleague.name,
          colleague.email,
          colleague.homechurch,
          colleague.password,
          colleague.profileImageUrl,
          colleague.phone,
          colleague.role,
        ]);
      } catch (error) {
        console.error("Error inserting colleague:", error);
        throw error;
      }
    }
  };

  const insertColleaguesApplied = async (db, colleaguesApplied) => {
    const insertQuery = `INSERT INTO colleaguesApplied
    (id, name, email, homechurch, password, profileImageUrl, phone, role)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;

    for (const colleague of colleaguesApplied) {
      try {
        await db.runAsync(insertQuery, [
          colleague.id,
          colleague.name,
          colleague.email,
          colleague.homechurch,
          colleague.password,
          colleague.profileImageUrl,
          colleague.phone,
          colleague.role,
        ]);
      } catch (error) {
        console.error("Error inserting applied colleague:", error);
        throw error;
      }
    }
  };

  const insertSongs = async (db, songs) => {
    const insertQuery = `INSERT INTO songs
    (id, title, artist, content, addedOn, editedBy, editedOn)
    VALUES (?, ?, ?, ?, ?, ?, ?)`;

    for (const song of songs) {
      try {
        await db.runAsync(insertQuery, [
          song.id,
          song.title,
          song.artist,
          song.content,
          song.addedOn,
          song.editedBy,
          song.editedOn,
        ]);
      } catch (error) {
        console.error("Error inserting song:", error);
        throw error;
      }
    }
  };

  // Modified login function
  const login = async () => {
    if (!validateForm()) {
      return;
    }

    setLoading(true);

    try {
      const response = await fetch(
        "https://kiamabackend.mathenoid.com/loginColleagues",
        {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify(formData),
        }
      );
      const responseData = await response.json();
      console.log("Server response:", responseData);

      if (responseData.success) {
        try {
          await storeDataInLocalDb(responseData.data);
          setUser(formData.username);

          setFormData({
            username: "",
            password: "",
          });

          navigation.navigate("(drawer)");
        } catch (dbError) {
          console.error("Database error:", dbError);
          Alert.alert(
            "Warning",
            "Logged in successfully, but there was an error storing data locally. Some features may not work offline."
          );
        }
      } else {
        Alert.alert("Error", responseData.errors);
      }
    } catch (error) {
      console.error("Login error:", error);
      Alert.alert(
        "Error",
        "An error occurred during login. Please try again later."
      );
    } finally {
      setLoading(false);
    }
  };

  const handleSignup = () => {
    navigation.navigate("signup");
  };

  const handleForgotPassword = () => {
    navigation.navigate("ForgotPassword");
  };

  return (
    <ScrollView contentContainerStyle={styles.scrollViewContainer}>
      <View style={styles.container}>
        <View style={styles.logoContainer}>
          <Image
            source={{
              uri: "https://images.fineartamerica.com/images-medium-large-5/open-bible-isolated-on-a-white-background-alexandr-grichenko.jpg",
            }}
            style={styles.logoImage}
          />
          <LinearGradient
            colors={["rgba(255,255,255,0)", "rgba(255,255,255,1)"]}
            style={styles.gradientMask}
          />
        </View>
        <View style={styles.welcomeTextContainer}>
          <Text style={styles.welcomeText}>Song Book</Text>
        </View>
        <View style={styles.formContainer}>
          <View style={styles.inputGroup}>
            <Text style={styles.label}>Username</Text>
            <TextInput
              style={styles.input}
              placeholder="Enter Username"
              value={formData.username}
              onChangeText={(text) => changeHandler("username", text)}
            />
          </View>
          <View style={styles.inputGroup}>
            <Text style={styles.label}>Password</Text>
            <View style={styles.passwordContainer}>
              <TextInput
                style={styles.passwordInput}
                placeholder="Password"
                secureTextEntry={!showPassword}
                value={formData.password}
                onChangeText={(text) => changeHandler("password", text)}
              />
              <TouchableOpacity
                onPress={toggleShowPassword}
                style={styles.eyeIcon}
              >
                <Ionicons
                  name={showPassword ? "eye-off" : "eye"}
                  size={24}
                  color="black"
                />
              </TouchableOpacity>
            </View>
            <TouchableOpacity onPress={handleForgotPassword}>
              <Text style={styles.forgotPasswordText}>Forgot password?</Text>
            </TouchableOpacity>
          </View>
          <TouchableOpacity
            style={styles.loginButton}
            onPress={login}
            disabled={loading}
          >
            {loading ? (
              <ActivityIndicator color="#fff" />
            ) : (
              <Text style={styles.loginButtonText}>Login</Text>
            )}
          </TouchableOpacity>
          <TouchableOpacity onPress={handleSignup}>
            <Text style={styles.registerText}>
              Don't have an account? register here
            </Text>
          </TouchableOpacity>
        </View>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  scrollViewContainer: {
    flexGrow: 1,
    backgroundColor: "#fff",
  },
  container: {
    flex: 1,
  },
  logoContainer: {
    height: "45%",
    position: "relative",
  },
  logoImage: {
    width: "100%",
    height: "100%",
    resizeMode: "cover",
  },
  gradientMask: {
    position: "absolute",
    left: 0,
    right: 0,
    bottom: 0,
    height: "50%",
  },
  welcomeTextContainer: {
    position: "absolute",
    top: "40%",
    left: 0,
    right: 0,
    alignItems: "center",
    justifyContent: "center",
  },
  forgotPasswordText: {
    fontFamily: "outfit",
    fontSize: 17,
    color: "#69c37b",
    letterSpacing: 2,
    transform: [{ rotate: "-5deg" }],
    textAlign: "right",
    marginTop: 10,
  },
  welcomeText: {
    fontFamily: "outfit",
    fontSize: 59,
    color: "#fff",
    textShadowColor: "rgba(0, 0, 0, 0.75)",
    textShadowOffset: { width: -1, height: 1 },
    textShadowRadius: 10,
    letterSpacing: 2,
    transform: [{ rotate: "-10deg" }],
  },
  loginText: {
    fontFamily: "outfit",
    fontSize: 20,
    color: "#69c37b",
  },
  formContainer: {
    backgroundColor: "#fff",
    padding: 20,
    borderTopRightRadius: 20,
    borderTopLeftRadius: 45,
    borderBottomLeftRadius: 20,
    borderBottomRightRadius: 45,
    elevation: 5,
    margin: 20,
    marginTop: 40,
  },
  inputGroup: {
    marginBottom: 15,
  },
  label: {
    fontSize: 20,
    marginBottom: 5,
    fontFamily: "outfit-medium",
  },
  input: {
    borderWidth: 1,
    borderColor: "#ddd",
    borderRadius: 5,
    padding: 10,
    fontSize: 16,
    fontFamily: "outfit",
  },
  passwordContainer: {
    flexDirection: "row",
    alignItems: "center",
    borderWidth: 1,
    borderColor: "#ddd",
    borderRadius: 5,
  },
  passwordInput: {
    flex: 1,
    padding: 10,
    fontSize: 16,
  },
  eyeIcon: {
    padding: 10,
  },
  loginButton: {
    backgroundColor: "#69c37b",
    borderRadius: 5,
    padding: 12,
    alignItems: "center",
    marginTop: 10,
  },
  loginButtonText: {
    color: "#fff",
    fontSize: 18,
    fontFamily: "outfit",
  },
  registerText: {
    margin: 10,
    fontSize: 17,
    color: "#69c37b",
    fontFamily: "outfit",
  },
});

export default LoginForm;
