import { html } from "/js/lib/lit-html.js";
import {
  isBlockedPost,
  isNotFoundPost,
  isUnavailablePost,
  getDisplayName,
  doHideAuthorOnUnauthenticated,
} from "/js/dataHelpers.js";
import { noop } from "/js/utils.js";
import { linkToPost } from "/js/navigation.js";
import { avatarTemplate } from "/js/templates/avatar.template.js";
import "/js/components/plugin-rich-text.js";
import { postEmbedTemplate } from "/js/templates/postEmbed.template.js";
import { postActionBarTemplate } from "/js/templates/postActionBar.template.js";
import { postHeaderTextTemplate } from "/js/templates/postHeaderText.template.js";
import { repostIconTemplate } from "/js/templates/icons/repostIcon.template.js";
import { pinIconTemplate } from "/js/templates/icons/pinIcon.template.js";
import { infoIconTemplate } from "/js/templates/icons/infoIcon.template.js";
import { cornerDownRightIconTemplate } from "/js/templates/icons/cornerDownRightIcon.template.js";
import { labelBadgesTemplate } from "/js/templates/labelBadges.template.js";
import { blockedPostTemplate } from "/js/templates/blockedPost.template.js";
import { notFoundPostTemplate } from "/js/templates/notFoundPost.template.js";
import { unavailablePostTemplate } from "/js/templates/unavailablePost.template.js";
import { moderationWarningTemplate } from "/js/templates/moderationWarning.template.js";
import "/js/components/lightbox-image-group.js";
import "/js/components/container-link.js";

function contentWarningTemplate({
  post,
  ignoreContentWarning,
  ignoreMuteWarning,
  children,
}) {
  const contentLabel = ignoreContentWarning ? null : post.contentLabel;
  if (contentLabel && contentLabel.visibility !== "ignore") {
    const isAuthorLabel = contentLabel.label.uri === post?.author?.did;
    return moderationWarningTemplate({
      className: "post-content-warning",
      labelDefinition: contentLabel.labelDefinition,
      labeler: contentLabel.labeler,
      isAuthorLabel,
      children,
    });
  }
  if (!ignoreMuteWarning) {
    // stop clicks here from bubbling to the surrounding post and triggering navigation
    const stopClick = (e) => e.stopPropagation();
    if (post.viewer?.hasMutedWord) {
      return html`<moderation-warning
        class="post-muted-warning"
        label="Hidden by muted word"
        icon-style="closed-eye"
        @click=${stopClick}
        >${children}</moderation-warning
      >`;
    }
    if (post.viewer?.isHidden) {
      return html`<moderation-warning
        class="post-muted-warning"
        label="Post hidden by you"
        icon-style="closed-eye"
        @click=${stopClick}
        >${children}</moderation-warning
      >`;
    }
  }
  return children;
}

export function smallPostTemplate({
  post,
  currentUser,
  isAuthenticated,
  isUserPost,
  postInteractionHandler,
  replyContext,
  repostAuthor,
  ignoreContentWarning = false,
  ignoreMuteWarning = false,
  isPinned = false,
  onClickShowLess = noop,
  onClickShowMore = noop,
  enableFeedFeedback = false,
  showReplyToLabel = false,
  replyToAuthor = null,
  lazyLoadImages = false,
  pluginService,
}) {
  if (isBlockedPost(post)) {
    return blockedPostTemplate();
  } else if (isNotFoundPost(post)) {
    return notFoundPostTemplate();
  } else if (isUnavailablePost(post)) {
    return unavailablePostTemplate();
  }
  const hideUnauthenticated =
    !isAuthenticated &&
    post.author &&
    doHideAuthorOnUnauthenticated(post.author);
  const postText = post.record.text || "";
  const content = html`
    <container-link
      class="post small-post clickable"
      data-testid="small-post"
      href=${linkToPost(post)}
    >
      <div class="post-content-with-space">
        <div class="post-content-left">
          ${replyContext === "parent" || replyContext === "reply"
            ? html`<div class="reply-context-line-in"></div>`
            : ""}
          <div>
            ${avatarTemplate({ author: post.author, lazyLoad: lazyLoadImages })}
          </div>
          ${replyContext === "root" || replyContext === "parent"
            ? html`<div class="reply-context-line-out-container">
                <div class="reply-context-line-out"></div>
              </div>`
            : ""}
        </div>
        <div class="post-content-right">
          ${isPinned
            ? html`<div class="pinned-label" data-testid="pinned-label">
                ${pinIconTemplate()} Pinned
              </div>`
            : ""}
          ${repostAuthor
            ? html`<div class="repost-label" data-testid="repost-label">
                ${repostIconTemplate()}
                ${repostAuthor.did === currentUser?.did
                  ? "Reposted by you"
                  : "Reposted by " + getDisplayName(repostAuthor)}
              </div>`
            : ""}
          ${postHeaderTextTemplate({
            author: post.author,
            timestamp: post.indexedAt,
          })}
          ${post.badgeLabels
            ? labelBadgesTemplate({ badgeLabels: post.badgeLabels })
            : ""}
          ${showReplyToLabel
            ? html`<div class="reply-to-author">
                ${cornerDownRightIconTemplate()} Replied to
                ${replyToAuthor
                  ? replyToAuthor.did === currentUser?.did
                    ? " you"
                    : html` ${getDisplayName(replyToAuthor)}`
                  : " user"}
              </div>`
            : ""}
          ${contentWarningTemplate({
            post,
            ignoreContentWarning,
            ignoreMuteWarning,
            children: html` <div class="post-body">
              ${hideUnauthenticated
                ? html`<div class="missing-post-indicator no-unauthenticated">
                    ${infoIconTemplate()} Sign-in required
                  </div>`
                : html`${postText.length > 0
                    ? html`<div class="post-text">
                        <plugin-rich-text
                          .pluginService=${pluginService}
                          .text=${postText}
                          .facets=${post.record.facets}
                          .transformContext=${{
                            surface: "smallPost",
                            uri: post.uri,
                            did: post.author?.did ?? null,
                          }}
                          truncate-urls
                        ></plugin-rich-text>
                      </div>`
                    : ""}
                  ${post.embed
                    ? html`<div class="post-embed">
                        ${postEmbedTemplate({
                          embed: post.embed,
                          mediaLabel: post.mediaLabel,
                          lazyLoadImages,
                          isAuthenticated,
                          pluginService,
                        })}
                      </div>`
                    : null}`}
            </div>`,
          })}
          ${postActionBarTemplate({
            post,
            isUserPost,
            isAuthenticated,
            currentUser,
            onClickReply: () => {
              window.router.go(linkToPost(post));
            },
            onClickLike: (post, doLike) =>
              postInteractionHandler.handleLike(post, doLike),
            onClickRepost: (post, doRepost) =>
              postInteractionHandler.handleRepost(post, doRepost),
            onClickQuotePost: (post) =>
              postInteractionHandler.handleQuotePost(post),
            onClickBookmark: (post, doBookmark) =>
              postInteractionHandler.handleBookmark(post, doBookmark),
            onClickShowLess,
            onClickShowMore,
            onClickHidePost: (post) =>
              postInteractionHandler.handleHidePost(post),
            onClickMute: (profile, doMute) =>
              postInteractionHandler.handleMuteAuthor(profile, doMute),
            onClickBlock: (profile, doBlock) =>
              postInteractionHandler.handleBlockAuthor(profile, doBlock),
            onClickDelete: (post) => {
              postInteractionHandler.handleDeletePost(post);
            },
            onClickPin: (post, doPin) =>
              postInteractionHandler.handlePinPost(post, doPin),
            onClickReport: (post) => postInteractionHandler.handleReport(post),
            enableFeedFeedback,
            pluginService,
          })}
        </div>
      </div>
    </container-link>
  `;

  return content;
}
