"use client";

import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import ProfileAvatar from "@/components/main/ProfileAvatar";
import useAxios from "@/hooks/useAxios";
import { User } from "@/types/types";

type ExploreAuthorProps = {
  userId: string;
  userName?: string;
  displayName: string;
  profileImage?: string;
};

export default function ExploreAuthor({
  userId,
  userName,
  displayName,
  profileImage,
}: ExploreAuthorProps) {
  const { request } = useAxios();

  const { data } = useQuery({
    queryKey: ["explore-author", userId],
    queryFn: () =>
      request<{ user: User }>("GET", `/profile/${userId}`, null, {
        noToast: true,
      }),
    enabled: Boolean(userId) && !profileImage,
    staleTime: 10 * 60 * 1000,
  });

  const avatarSrc = profileImage || data?.user?.profile_image;

  const content = (
    <>
      <ProfileAvatar
        src={avatarSrc}
        alt={userName || displayName}
        size="xs"
        rounded="full"
      />
      <span className="truncate text-xs font-medium text-neutral-600 dark:text-neutral-300">
        {userName ? `@${userName}` : displayName}
      </span>
    </>
  );

  if (userName) {
    return (
      <Link
        href={`/users/${userName}`}
        onClick={(e) => e.stopPropagation()}
        className="gentle-transition flex min-w-0 items-center gap-1.5 active:opacity-70"
      >
        {content}
      </Link>
    );
  }

  return (
    <span className="flex min-w-0 items-center gap-1.5">{content}</span>
  );
}
