"use client";

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { apiClient } from '@/lib/api';

interface User {
  id: string;
  email: string;
  name: string;
  role: 'USER' | 'ADMIN';
  createdAt?: string;
}

interface AuthContextType {
  user: User | null;
  login: (email: string, password: string) => Promise<{ success: boolean; error?: string }>;
  register: (name: string, email: string, password: string) => Promise<{ success: boolean; error?: string }>;
  logout: () => void;
  forgotPassword: (email: string) => Promise<{ success: boolean; error?: string }>;
  resetPassword: (token: string, password: string) => Promise<{ success: boolean; error?: string }>;
  loading: boolean;
  isAuthenticated: boolean;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

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

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Check if user is logged in on app start
    const checkAuth = async () => {
      try {
        const token = localStorage.getItem('auth_token');
        if (token) {
          // Validate token with backend
          const response = await apiClient.verifyToken(token);
          if (response.data && typeof response.data === 'object' && 'valid' in response.data && 'user' in response.data) {
            setUser((response.data as { user: User }).user);
          } else {
            // Token is invalid, clear storage
            localStorage.removeItem('auth_token');
            localStorage.removeItem('user_data');
          }
        }
      } catch (error) {
        console.error('Auth check failed:', error);
        localStorage.removeItem('auth_token');
        localStorage.removeItem('user_data');
      } finally {
        setLoading(false);
      }
    };

    checkAuth();
  }, []);

  const login = async (email: string, password: string): Promise<{ success: boolean; error?: string }> => {
    try {
      setLoading(true);
      
      const response = await apiClient.login(email, password);
      
      if (response.data && typeof response.data === 'object' && 'user' in response.data && 'token' in response.data) {
        const { user, token } = response.data as { user: User; token: string };
        
        localStorage.setItem('auth_token', token);
        localStorage.setItem('user_data', JSON.stringify(user));
        setUser(user);
        
        return { success: true };
      }
      
      return { success: false, error: response.error || 'A apărut o eroare la autentificare' };
    } catch (error) {
      console.error('Login failed:', error);
      return { success: false, error: 'A apărut o eroare de rețea' };
    } finally {
      setLoading(false);
    }
  };

  const register = async (name: string, email: string, password: string): Promise<{ success: boolean; error?: string }> => {
    try {
      setLoading(true);
      
      const response = await apiClient.register(name, email, password);
      
      if (response.data && typeof response.data === 'object' && 'user' in response.data && 'token' in response.data) {
        const { user, token } = response.data as { user: User; token: string };
        
        localStorage.setItem('auth_token', token);
        localStorage.setItem('user_data', JSON.stringify(user));
        setUser(user);
        
        return { success: true };
      }
      
      return { success: false, error: response.error || 'A apărut o eroare la crearea contului' };
    } catch (error) {
      console.error('Registration failed:', error);
      return { success: false, error: 'A apărut o eroare de rețea' };
    } finally {
      setLoading(false);
    }
  };

  const logout = () => {
    localStorage.removeItem('auth_token');
    localStorage.removeItem('user_data');
    setUser(null);
  };

  const forgotPassword = async (email: string): Promise<{ success: boolean; error?: string }> => {
    try {
      setLoading(true);
      
      const response = await apiClient.forgotPassword(email);
      
      if (response.data || response.message) {
        return { success: true };
      }
      
      return { success: false, error: response.error || 'A apărut o eroare la trimiterea email-ului' };
    } catch (error) {
      console.error('Forgot password failed:', error);
      return { success: false, error: 'A apărut o eroare de rețea' };
    } finally {
      setLoading(false);
    }
  };

  const resetPassword = async (token: string, password: string): Promise<{ success: boolean; error?: string }> => {
    try {
      setLoading(true);
      
      const response = await apiClient.resetPassword(token, password);
      
      if (response.data || response.message) {
        return { success: true };
      }
      
      return { success: false, error: response.error || 'A apărut o eroare la resetarea parolei' };
    } catch (error) {
      console.error('Reset password failed:', error);
      return { success: false, error: 'A apărut o eroare de rețea' };
    } finally {
      setLoading(false);
    }
  };

  const value: AuthContextType = {
    user,
    login,
    register,
    logout,
    forgotPassword,
    resetPassword,
    loading,
    isAuthenticated: !!user
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};
