import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { useAuth } from "../hooks/useAuth.ts";
import { useFollows } from "../hooks/useFollows.ts";

interface FollowUserButtonProps {
  targetUserId: string;
  targetUsername: string;
}

interface FollowPlaylistButtonProps {
  targetPlaylistId: string;
  isPublic: boolean;
}

export function FollowUserButton(
  { targetUserId, targetUsername }: FollowUserButtonProps,
) {
  const { user } = useAuth();
  const { followedUserIds, followUser, unfollowUser, isLoaded } = useFollows();

  if (!user || user.id === targetUserId) return null;

  const isFollowing = followedUserIds.has(targetUserId);

  return (
    <button
      type="button"
      className={`follow-btn${isFollowing ? " follow-btn--following" : ""}`}
      disabled={!isLoaded}
      onClick={() =>
        isFollowing ? unfollowUser(targetUserId) : followUser(targetUserId)}
      aria-label={isFollowing
        ? t`Unfollow ${targetUsername}`
        : t`Follow ${targetUsername}`}
    >
      {isFollowing ? <Trans>Following</Trans> : <Trans>Follow</Trans>}
    </button>
  );
}

export function FollowPlaylistButton(
  { targetPlaylistId, isPublic }: FollowPlaylistButtonProps,
) {
  const { user } = useAuth();
  const { followedPlaylistIds, followPlaylist, unfollowPlaylist, isLoaded } =
    useFollows();

  if (!user || !isPublic) return null;

  const isFollowing = followedPlaylistIds.has(targetPlaylistId);

  return (
    <button
      type="button"
      className={`follow-btn${isFollowing ? " follow-btn--following" : ""}`}
      disabled={!isLoaded}
      onClick={() =>
        isFollowing
          ? unfollowPlaylist(targetPlaylistId)
          : followPlaylist(targetPlaylistId)}
      aria-label={isFollowing ? t`Unfollow playlist` : t`Follow playlist`}
    >
      {isFollowing ? <Trans>Following</Trans> : <Trans>Follow</Trans>}
    </button>
  );
}
