
import { createContext, useContext, useState, useEffect } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { toast } from 'react-toastify';

const AuthContext = createContext();

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

  // Set axios defaults
  axios.defaults.withCredentials = true;

  // Check auth status on app load
  useEffect(() => {
    const checkAuth = async () => {
      try {
        const res = await axios.get('/api/auth/me');
        setUser(res.data.user);
      } catch (err) {
        setUser(null);
      } finally {
        setLoading(false);
      }
    };

    checkAuth();
  }, []);

  // Register user
  const register = async (formData) => {
    try {
      setLoading(true);
      const res = await axios.post('/api/auth/register', formData);
      setUser(res.data.user);
      toast.success('ثبت‌نام با موفقیت انجام شد');
      navigate('/dashboard');
      return res.data;
    } catch (err) {
      const errorMessage = err.response?.data?.message || 'خطا در ثبت‌نام';
      toast.error(errorMessage);
      throw errorMessage;
    } finally {
      setLoading(false);
    }
  };

  // Login user
  const login = async (formData) => {
    try {
      setLoading(true);
      const res = await axios.post('/api/auth/login', formData);
      setUser(res.data.user);
      toast.success('ورود با موفقیت انجام شد');
      navigate('/dashboard');
      return res.data;
    } catch (err) {
      const errorMessage = err.response?.data?.message || 'خطا در ورود';
      toast.error(errorMessage);
      throw errorMessage;
    } finally {
      setLoading(false);
    }
  };

  // Logout user
  const logout = async () => {
    try {
      await axios.get('/api/auth/logout');
      setUser(null);
      toast.success('خروج با موفقیت انجام شد');
      navigate('/');
    } catch (err) {
      toast.error('خطا در خروج از سیستم');
    }
  };

  // Check if user is authenticated
  const isAuthenticated = () => {
    return !!user;
  };

  // Check if user has specific role
  const hasRole = (role) => {
    return user?.role === role;
  };

  return (
    <AuthContext.Provider 
      value={{ 
        user, 
        loading, 
        register, 
        login, 
        logout, 
        isAuthenticated,
        hasRole
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext);
}
