'use client';

import { useQuery } from '@tanstack/react-query';
import { useMemo } from 'react';

import Avatar from '@/components/image/Avatar';
import { useApiClient } from '@/lib/apiClient';
import { FALLBACK_IMAGE_URL } from '@/utils/constants';
import { isValidResourceUrl } from '@/utils/utils';

type UserHoverPreviewProps = {
  handle: string;
};

export default function UserHoverPreview({ handle }: UserHoverPreviewProps) {
  const apiClient = useApiClient();

  const queryKey = useMemo(() => ['user-hover-preview', handle], [handle]);

  const { data } = useQuery({
    queryKey,
    enabled: Boolean(handle),
    queryFn: async () => {
      try {
        const response = await apiClient.GET('/api/profiles/{handle}', {
          params: {
            path: { handle },
            query: {
              page: 1,
              playlists_sort_by: 'upvote_count',
              clips_sort_by: 'upvote_count',
              include_hooks: false,
              include_artist_profile: false,
              page_size: 1,
            },
          },
        });
        return response.data as any;
      } catch (err) {
        return undefined;
      }
    },
    staleTime: 1000 * 60 * 5,
  });

  const displayName: string | undefined = data?.display_name || data?.name;
  const avatarUrl: string | undefined = data?.avatar_image_url;
  const followersCount: number | undefined = data?.stats?.followers_count;

  const safeAvatar = isValidResourceUrl(avatarUrl)
    ? avatarUrl
    : FALLBACK_IMAGE_URL;

  return (
    <div className='pointer-events-auto absolute bottom-0 left-1/2 w-[260px] -translate-x-1/2 rounded-xl border border-white/10 bg-background-glass-thick p-3 shadow-xl backdrop-blur-md'>
      <div className='flex items-center gap-3'>
        <div className='h-12 w-12 overflow-hidden rounded-full'>
          <Avatar
            src={safeAvatar}
            displayName={displayName || `@${handle}`}
            size={48}
            className='h-full w-full object-cover'
          />
        </div>
        <div className='min-w-0 flex-1'>
          <div className='truncate font-medium text-white'>
            {displayName || `@${handle}`}
          </div>
          <div className='truncate text-sm text-white/70'>@{handle}</div>
          {typeof followersCount === 'number' && (
            <div className='text-xs text-white/60'>
              {followersCount.toLocaleString()} followers
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
