import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { UserAvatar } from '@/components/ui/user-avatar';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { User, Settings, LogOut } from 'lucide-react';
import { useAuth } from '@/hooks/useAuth';
import { useProfile } from '@/hooks/useProfile';
import { useToast } from '@/hooks/use-toast';
import { useAuthModal } from '@/hooks/useAuthModal';
import { getErrorMessage } from '@/lib/errorHandler';

export function AuthButtons() {
  const { user, loading: authLoading, signOut } = useAuth();
  const { data: profile, isLoading: profileLoading } = useProfile(user?.id);
  const navigate = useNavigate();
  const { toast } = useToast();
  const { openAuthModal } = useAuthModal();
  const [loggingOut, setLoggingOut] = useState(false);
  const handleSignOut = async () => {
    setLoggingOut(true);
    try {
      await signOut();
      toast({
        title: "Signed out",
        description: "You've been signed out successfully."
      });
      navigate('/');
    } catch (error: unknown) {
      const errorMsg = getErrorMessage(error);
      toast({
        variant: "destructive",
        title: "Error signing out",
        description: errorMsg
      });
    } finally {
      setLoggingOut(false);
    }
  };
  
  // Show loading skeleton only during initial auth check
  if (authLoading) {
    return (
      <div className="flex gap-2 items-center">
        <div className="h-8 w-16 bg-muted animate-pulse rounded" />
        <div className="h-8 w-8 bg-muted animate-pulse rounded-full" />
      </div>
    );
  }
  
  if (!user) {
    return (
      <>
        <Button
          variant="ghost" 
          size="sm" 
          onClick={() => openAuthModal('signin')}
        >
          Sign In
        </Button>
        <Button 
          size="sm" 
          className="bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90" 
          onClick={() => openAuthModal('signup')}
        >
          Join ThrillWiki
        </Button>
      </>
    );
  }
  return <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="ghost" className="relative h-8 w-8 rounded-full">
          <UserAvatar 
            key={profile?.avatar_url || 'no-avatar'}
            avatarUrl={profile?.avatar_url}
            fallbackText={profile?.display_name || profile?.username || user.email || 'U'}
            size="sm"
          />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent className="w-56" align="end" forceMount>
        <DropdownMenuLabel className="font-normal">
          <div className="flex flex-col space-y-1">
            <p className="text-sm font-medium leading-none">
              {profile?.display_name || profile?.username}
            </p>
            <p className="text-xs leading-none text-muted-foreground">
              {user.email}
            </p>
          </div>
        </DropdownMenuLabel>
        <DropdownMenuSeparator />
        <DropdownMenuItem onClick={() => navigate('/profile')}>
          <User className="mr-2 h-4 w-4" />
          <span>Profile</span>
        </DropdownMenuItem>
        
        <DropdownMenuItem onClick={() => navigate('/settings')}>
          <Settings className="mr-2 h-4 w-4" />
          <span>Settings</span>
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem onClick={handleSignOut} disabled={loggingOut}>
          <LogOut className="mr-2 h-4 w-4" />
          <span>{loggingOut ? 'Signing out...' : 'Sign out'}</span>
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>;
}