import { useRef, useState } from "react";
import { t } from "@lingui/core/macro";
import { API_URL } from "../config/api.ts";
import { UserListPopover } from "./UserListPopover.tsx";

interface LikeButtonProps {
  commentId: string;
  count: number;
  liked: boolean;
  disabled?: boolean;
  onLike: (commentId: string) => void;
  onUnlike: (commentId: string) => void;
}

export function LikeButton(
  { commentId, count, liked, disabled, onLike, onUnlike }: LikeButtonProps,
) {
  const [popoverOpen, setPopoverOpen] = useState(false);
  const countRef = useRef<HTMLSpanElement>(null);

  return (
    <>
      <button
        type="button"
        className={`comment-action-btn${
          liked ? " comment-action-btn--liked" : ""
        }`}
        onClick={() => liked ? onUnlike(commentId) : onLike(commentId)}
        disabled={disabled}
        aria-label={liked ? t`Remove like` : t`Like`}
        title={disabled ? t`Log in to like` : undefined}
      >
        ♥{" "}
        {count > 0
          ? (
            <span
              ref={countRef}
              className="like-count-clickable"
              onClick={(e) => {
                e.stopPropagation();
                setPopoverOpen((o) => !o);
              }}
            >
              {count}
            </span>
          )
          : count}
      </button>
      {popoverOpen && (
        <UserListPopover
          anchorRef={countRef}
          onClose={() => setPopoverOpen(false)}
          fetchUrl={`${API_URL}/api/comments/${commentId}/likers`}
        />
      )}
    </>
  );
}
