import { useState, useEffect, useCallback } from 'react';
import { authApi } from '../services/api';
import type { User, LoginRequest } from '../types';

export function useAuth() {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const checkAuth = useCallback(async () => {
    const token = localStorage.getItem('token');
    if (!token) {
      setLoading(false);
      return;
    }

    try {
      const userData = await authApi.me();
      setUser(userData);
    } catch {
      localStorage.removeItem('token');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    checkAuth();
  }, [checkAuth]);

  const login = async (data: LoginRequest) => {
    setError(null);
    try {
      const response = await authApi.login(data);
      localStorage.setItem('token', response.access_token);
      setUser(response.user);
      return true;
    } catch (err) {
      setError('登入失敗，請檢查帳號密碼');
      return false;
    }
  };

  const register = async (data: LoginRequest) => {
    setError(null);
    try {
      await authApi.register(data);
      return await login(data);
    } catch (err) {
      setError('註冊失敗，該 Email 可能已被使用');
      return false;
    }
  };

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

  return {
    user,
    loading,
    error,
    isAuthenticated: !!user,
    login,
    register,
    logout,
  };
}
