// UserContextProvider.js
import React, { useState, useEffect } from "react";
import UserContext from "./UserContext";
import axios from "axios";
import { SQLiteProvider } from "expo-sqlite";

const UserContextProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [userRole, setUserRole] = useState(null);
  const [dbInitialized, setDbInitialized] = useState(false);

  useEffect(() => {
    const fetchUserRole = async () => {
      if (user) {
        try {
          const response = await axios.post(
            "https://kiamabackend.mathenoid.com/api/getUserRole",
            { user }
          );
          if (response.data.success) {
            setUserRole(response.data.role);
          } else {
            console.error("Failed to fetch user role:", response.data.message);
            setUserRole(null);
          }
        } catch (error) {
          console.error("Error fetching user role:", error);
          setUserRole(null);
        }
      } else {
        setUserRole(null);
      }
    };

    fetchUserRole();
  }, [user]);

  const initializeDatabase = async (db) => {
    if (dbInitialized) return;

    try {
      // Clear and recreate the colleagues table
      await db.execAsync(`
        DROP TABLE IF EXISTS colleagues;
        CREATE TABLE IF NOT EXISTS colleagues (
          id INTEGER PRIMARY KEY,
          email VARCHAR(100) NOT NULL UNIQUE,
          name VARCHAR(255) NOT NULL,
          password VARCHAR(255) NOT NULL,
          profileImageUrl VARCHAR(255) NOT NULL,
          phone VARCHAR(20) NOT NULL,
          role VARCHAR(20) NOT NULL,
          homechurch VARCHAR(100) NOT NULL
        )
      `);

      // Clear and recreate the colleaguesApplied table
      await db.execAsync(`
        DROP TABLE IF EXISTS colleaguesApplied;
        CREATE TABLE IF NOT EXISTS colleaguesApplied (
          id INTEGER PRIMARY KEY,
          email VARCHAR(100) NOT NULL UNIQUE,
          name VARCHAR(255) NOT NULL,
          password VARCHAR(255) NOT NULL,
          profileImageUrl VARCHAR(255) NOT NULL,
          phone VARCHAR(20) NOT NULL,
          role VARCHAR(20) NOT NULL,
          homechurch VARCHAR(100) NOT NULL
        )
      `);

      // Clear and recreate the songs table
      await db.execAsync(`
        DROP TABLE IF EXISTS songs;
        CREATE TABLE IF NOT EXISTS songs (
          id INTEGER PRIMARY KEY,
          title VARCHAR(255) NOT NULL,
          content TEXT NOT NULL,
          artist VARCHAR(255) NOT NULL,
          addedOn TIMESTAMP NOT NULL,
          editedBy VARCHAR(100) DEFAULT NULL,
          editedOn VARCHAR(100) DEFAULT NULL
        )
      `);

      setDbInitialized(true);
      console.log("Database initialized: tables cleared and recreated");
    } catch (error) {
      console.error("Error when initializing database:", error);
      throw error;
    }
  };

  return (
    <SQLiteProvider databaseName="songbook.db" onInit={initializeDatabase}>
      <UserContext.Provider value={{ user, setUser, userRole, dbInitialized }}>
        {children}
      </UserContext.Provider>
    </SQLiteProvider>
  );
};

export default UserContextProvider;
