import React, { createContext, useState, useContext, useEffect } from 'react';
import axios from 'axios';

const AuthContext = createContext();

const API_URL = process.env.REACT_APP_BACKEND_URL;

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [token, setToken] = useState(localStorage.getItem('token'));

  useEffect(() => {
    const initAuth = async () => {
      const storedToken = localStorage.getItem('token');
      if (storedToken) {
        try {
          const response = await axios.get(`${API_URL}/api/auth/me`, {
            headers: { Authorization: `Bearer ${storedToken}` }
          });
          setUser(response.data);
          setToken(storedToken);
        } catch (error) {
          localStorage.removeItem('token');
          setToken(null);
        }
      }
      setLoading(false);
    };
    initAuth();
  }, []);

  const login = async (email, password) => {
    const response = await axios.post(`${API_URL}/api/auth/login`, { email, password });
    const { access_token, user: userData } = response.data;
    localStorage.setItem('token', access_token);
    setToken(access_token);
    setUser(userData);
    return userData;
  };

  const logout = () => {
    localStorage.removeItem('token');
    setToken(null);
    setUser(null);
  };

  const register = async (userData) => {
    await axios.post(`${API_URL}/api/auth/register`, userData);
  };

  const refreshUser = async () => {
    try {
      const currentToken = localStorage.getItem('token');
      if (!currentToken) {
        throw new Error('No token available');
      }

      const response = await axios.get(`${API_URL}/api/auth/me`, {
        headers: { Authorization: `Bearer ${currentToken}` }
      });
      setUser(response.data);
      return response.data;
    } catch (error) {
      console.error('Failed to refresh user:', error);
      // If token expired, logout
      if (error.response?.status === 401) {
        logout();
      }
      throw error;
    }
  };

  const forgotPassword = async (email) => {
    const response = await axios.post(`${API_URL}/api/auth/forgot-password`, { email });
    return response.data;
  };

  const resetPassword = async (token, newPassword) => {
    const response = await axios.post(`${API_URL}/api/auth/reset-password`, {
      token,
      new_password: newPassword
    });
    return response.data;
  };

  const changePassword = async (currentPassword, newPassword) => {
    const currentToken = localStorage.getItem('token');
    if (!currentToken) {
      throw new Error('Not authenticated');
    }

    const response = await axios.put(
      `${API_URL}/api/users/change-password`,
      {
        current_password: currentPassword,
        new_password: newPassword
      },
      {
        headers: { Authorization: `Bearer ${currentToken}` }
      }
    );

    // Refresh user data to clear force_password_change flag if it was set
    await refreshUser();

    return response.data;
  };

  const resendVerificationEmail = async () => {
    const currentToken = localStorage.getItem('token');
    if (!currentToken) {
      throw new Error('Not authenticated');
    }

    const response = await axios.post(
      `${API_URL}/api/auth/resend-verification-email`,
      {},
      {
        headers: { Authorization: `Bearer ${currentToken}` }
      }
    );

    return response.data;
  };

  return (
    <AuthContext.Provider value={{
      user,
      token,
      login,
      logout,
      register,
      refreshUser,
      forgotPassword,
      resetPassword,
      changePassword,
      resendVerificationEmail,
      loading
    }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);
