// context/AuthContext.js
"use client";
import { createContext, useContext, useState, useEffect } from "react";
import { account,ID } from "../lib/appwrite";

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    checkSession();
  }, []);

  const checkSession = async () => {
    try {
      const currentUser = await account.get();
      setUser(currentUser);
    } catch (error) {
      setUser(null);
    } finally {
      setLoading(false);
    }
  };

  const login = async (email, password) => {
    try {
      await account.createEmailPasswordSession(email, password);
      const currentUser = await account.get();
      setUser(currentUser);
      return currentUser;
    } catch (error) {
      throw error;
    }
  };

  const register = async (email, password, name) => {
    try {
      await account.create(ID.unique(), email, password, name);
      await account.createEmailPasswordSession(email, password);
      const currentUser = await account.get();
      setUser(currentUser);
      return currentUser;
    } catch (error) {
      throw error;
    }
  };

  const logout = async () => {
    try {
      await account.deleteSession("current");
      setUser(null);
    } catch (error) {
      throw error;
    }
  };
// --------password reset------------------------
const sendPasswordResetEmail = async (email) => {
  try {
    await account.createRecovery(
      email,
      `${window.location.origin}/reset-password` // Your reset password URL
    );
    return true;
  } catch (error) {
    console.error("Password reset error:", error);
    throw error;
  }
};

const resetPassword = async (userId, secret, newPassword, confirmPassword) => {
  if (newPassword !== confirmPassword) {
    throw new Error("Passwords don't match");
  }
  
  try {
    await account.updateRecovery(
      userId,
      secret,
      newPassword,
      confirmPassword
    );
    return true;
  } catch (error) {
    console.error("Password update error:", error);
    throw error;
  }
};

// -----------------------------------------------
  return (
    <AuthContext.Provider
      value={{
        user,
        loading,
        isAuthenticated: !!user,
        login,
        register,
        logout,
        sendPasswordResetEmail,
    resetPassword,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
};