import { useState, useCallback } from 'react';
import { LoginCredentials, SignupData, AuthError, AuthState } from '../types/auth';

export const useAuth = () => {
  const [state, setState] = useState<AuthState>({
    isLoading: false,
    error: null,
    user: null
  });

  const login = useCallback(async (credentials: LoginCredentials) => {
    try {
      setState(prev => ({ ...prev, isLoading: true, error: null }));
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(credentials)
      });
      const data = await response.json();
      if (!response.ok) throw new Error(data.message);
      setState(prev => ({ ...prev, user: data.user }));
    } catch (err) {
      setState(prev => ({ ...prev, error: { message: err.message } }));
    } finally {
      setState(prev => ({ ...prev, isLoading: false }));
    }
  }, []);

  const signup = useCallback(async (data: SignupData) => {
    try {
      setState(prev => ({ ...prev, isLoading: true, error: null }));
      const response = await fetch('/api/auth/signup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
      });
      const result = await response.json();
      if (!response.ok) throw new Error(result.message);
      setState(prev => ({ ...prev, user: result.user }));
    } catch (err) {
      setState(prev => ({ ...prev, error: { message: err.message } }));
    } finally {
      setState(prev => ({ ...prev, isLoading: false }));
    }
  }, []);

  return { ...state, login, signup };
}