import { useState, useEffect, useCallback } from 'react';
import {
  googleLogin,
  getMe,
  logout as logoutApi,
} from '../services/authApi';
import type { AuthUser } from '../services/authApi';

interface AuthState {
  user: AuthUser | null;
  isLoading: boolean;
  isAuthenticated: boolean;
}

const DEV_USER: AuthUser = {
  email: 'dev@gcsc.co.kr',
  name: 'Developer',
};

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

  useEffect(() => {
    let cancelled = false;

    getMe()
      .then((user) => {
        if (!cancelled) {
          setState({ user, isLoading: false, isAuthenticated: true });
        }
      })
      .catch(() => {
        if (!cancelled) {
          setState({ user: null, isLoading: false, isAuthenticated: false });
        }
      });

    return () => {
      cancelled = true;
    };
  }, []);

  const login = useCallback(async (credential: string) => {
    setState((prev) => ({ ...prev, isLoading: true }));
    try {
      const user = await googleLogin(credential);
      setState({ user, isLoading: false, isAuthenticated: true });
    } catch {
      setState({ user: null, isLoading: false, isAuthenticated: false });
      throw new Error('Login failed');
    }
  }, []);

  const devLogin = useCallback(() => {
    setState({ user: DEV_USER, isLoading: false, isAuthenticated: true });
  }, []);

  const logout = useCallback(async () => {
    try {
      await logoutApi();
    } finally {
      setState({ user: null, isLoading: false, isAuthenticated: false });
    }
  }, []);

  return {
    user: state.user,
    isLoading: state.isLoading,
    isAuthenticated: state.isAuthenticated,
    login,
    devLogin,
    logout,
  };
}
