import React from 'react';
import { useAuth } from 'react-oidc-context';
import { LogIn, LogOut, User, Loader2 } from 'lucide-react';

export const AuthButton: React.FC = () => {
  const auth = useAuth();

  if (auth.isLoading) {
    return (
      <div className="flex items-center gap-2 bg-white/10 px-4 py-2 rounded-xl">
        <Loader2 className="animate-spin" size={20} />
      </div>
    );
  }

  if (auth.error) {
    return (
      <div className="flex items-center gap-2 bg-red-500/20 px-4 py-2 rounded-xl text-sm">
        <span>Auth Error</span>
      </div>
    );
  }

  if (auth.isAuthenticated) {
    return (
      <div className="flex items-center gap-3">
        <div className="flex items-center gap-2 bg-white/10 px-3 py-2 rounded-xl">
          <User size={18} />
          <span className="font-bold text-sm">
            {auth.user?.profile.preferred_username || auth.user?.profile.name || 'User'}
          </span>
        </div>
        <button
          onClick={() => auth.signoutRedirect()}
          className="p-2 bg-white/10 rounded-xl hover:bg-white/20 transition"
          title="Sign out"
        >
          <LogOut size={20} />
        </button>
      </div>
    );
  }

  return (
    <button
      onClick={() => auth.signinRedirect()}
      className="flex items-center gap-2 bg-white/10 px-4 py-2 rounded-xl hover:bg-white/20 transition font-bold"
    >
      <LogIn size={20} />
      Sign In
    </button>
  );
};
