
import React, { createContext, useContext, useState, ReactNode } from 'react';
import { User, UserRole } from '../types';

// Mock Users Database
const MOCK_USERS: User[] = [
  {
    id: 'superadmin-1',
    name: 'Dev Admin',
    email: 'admin@photum.com',
    role: UserRole.SUPERADMIN,
    avatar: 'https://i.pravatar.cc/150?u=admin'
  },
  {
    id: 'owner-1',
    name: 'PHOTUM CEO',
    email: 'empresa@photum.com',
    role: UserRole.BUSINESS_OWNER,
    avatar: 'https://i.pravatar.cc/150?u=ceo'
  },
  {
    id: 'photographer-1',
    name: 'COLABORADOR PHOTUM',
    email: 'foto@photum.com',
    role: UserRole.PHOTOGRAPHER,
    avatar: 'https://i.pravatar.cc/150?u=photo'
  },
  {
    id: 'client-1',
    name: 'PARCEIRO PHOTUM',
    email: 'cliente@photum.com',
    role: UserRole.EVENT_OWNER,
    avatar: 'https://i.pravatar.cc/150?u=client'
  }
];

interface AuthContextType {
  user: User | null;
  login: (email: string) => Promise<boolean>;
  logout: () => void;
  availableUsers: User[]; // Helper for the login screen demo
}

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

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

  const login = async (email: string) => {
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 800));
    
    const foundUser = MOCK_USERS.find(u => u.email === email);
    if (foundUser) {
      setUser(foundUser);
      return true;
    }
    return false;
  };

  const logout = () => {
    setUser(null);
  };

  return (
    <AuthContext.Provider value={{ user, login, logout, availableUsers: MOCK_USERS }}>
      {children}
    </AuthContext.Provider>
  );
};

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