"use client";

import Image from "next/image";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { getDefaultProfileImage } from "@/lib/helpers";

import { type Reply } from "./replyDetailTypes";
import type { useReplyDetail } from "./useReplyDetail";
import ReplyActionsMenu from "./ReplyActionsMenu";
import ReplyEngagementBar from "./ReplyEngagementBar";
import CommunityImageStrip from "./CommunityImageStrip";
import { pickLocalized } from "@/features/shared/types/cms";

const asset = (path: string) => `/assets/${path}`;

/**
 * One reply under the reply being viewed.
 *
 * The thread does not nest further: tapping a child opens its own page, which
 * then renders that child's children with this same component.
 */
export default function ChildReplyRow({
  childReply,
  screen,
}: {
  childReply: Reply;
  /* Drives the divider: the last row in the list has none. */
  isLast: boolean;
  screen: ReturnType<typeof useReplyDetail>;
}) {
  const { t } = useTranslation();
  const {
    selectedLanguage,
    authToken,
    showDropdown,
    setShowDropdown,
    handleReplyLike,
    likeMutation,
    setReplyToId,
    setOpen,
    registerDropdownRef,
    handleEdit,
    handleDelete,
    handleImageClick,
    handleNavigateToReply,
    navigateToProfile,
  } = screen;

  const openThisReply = () => handleNavigateToReply(childReply.id);

  return (
    <div
      className="relative my-4 ms-3 grid grid-cols-[32px_minmax(0,1fr)] items-start gap-x-2 border-s-2 border-[#E4E6EB] ps-3 sm:ms-6"
    >
      {childReply.is_creator && !childReply.is_deleted && (
        <div
          className={`absolute z-10 top-0 ${
            selectedLanguage === "ar" ? "left-4" : "right-4"
          }`}
          ref={registerDropdownRef(`reply-${childReply.id}`)}
        >
          <ReplyActionsMenu
            dropdownKey={`reply-${childReply.id}`}
            selectedLanguage={selectedLanguage}
            showDropdown={showDropdown}
            setShowDropdown={setShowDropdown}
            onEdit={() => handleEdit(String(childReply.id))}
            onDelete={() => handleDelete(String(childReply.id))}
            iconClassName="text-primary-5 text-lg"
          />
        </div>
      )}

      {!childReply.isPlaceholder ? (
        <>
          <div className="contents">
            <Image
              src={
                childReply.user.profile_pic ||
                getDefaultProfileImage(
                  childReply.user.gender_display?.value_en,
                  asset("profile/male_profile.svg"),
                  asset("profile/female_profile.svg"),
                  asset("profile/org_profile.svg")
                )
              }
              alt=""
              width={59}
              height={59}
              unoptimized
              className="col-start-1 row-span-2 h-8 w-8 shrink-0 cursor-pointer rounded-full object-cover"
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                navigateToProfile(childReply.user);
              }}
              onKeyDown={(e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  navigateToProfile(childReply.user);
                }
              }}
              role="button"
              tabIndex={0}
            />
            {/*
              The name is both a heading and a link to the thread. It used to
              be one element doing both — an `<h3 role="button">` — which
              trades the heading away: a screen reader's heading list is how a
              reader skims a long thread, and an element re-roled as a button
              is no longer in it. A `<button>` *inside* the heading keeps both,
              and gets focus, Enter and Space from the platform rather than
              from a hand-written `onKeyDown`. Tailwind's preflight makes a
              bare button inherit font, colour and weight, so this renders
              exactly as before.
            */}
            <h3 className="col-start-2 min-w-0 rounded-t-2xl bg-[#F0F2F5] px-3 pb-1 pt-2 text-sm font-bold">
              <button
                type="button"
                className="cursor-pointer !whitespace-normal text-start hover:underline"
                onClick={openThisReply}
              >
                {childReply.user.full_name}
              </button>
            </h3>
          </div>

          <div
            className="col-start-2 -mt-1 mb-1 min-w-0 cursor-pointer rounded-b-2xl bg-[#F0F2F5] px-3 pb-3"
            onClick={openThisReply}
            onKeyDown={(e) => {
              if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                openThisReply();
              }
            }}
            role="button"
            tabIndex={0}
          >
            <p className="whitespace-pre-wrap text-sm leading-relaxed text-[#303030] [overflow-wrap:anywhere]">
              {pickLocalized(childReply.text_en, childReply.text_ar, selectedLanguage)}
            </p>
          </div>

          {/* No `stopPropagation`: the strip is a *sibling* of the author
              name and the text block, which are the only two things carrying
              `openThisReply` — nothing above it listens for a click. */}
          <div className="col-start-2 my-2 min-w-0"><CommunityImageStrip
            images={childReply.reply_images ?? []}
            onImageClick={handleImageClick}
            altPrefix="Reply"
          /></div>

          <ReplyEngagementBar
            className="col-start-2 flex flex-wrap items-center gap-3 px-2 pt-1"
            likesCount={childReply.likes_count}
            replyCount={childReply.child_replies?.length || 0}
            likeDisabled={likeMutation.isPending}
            onLike={(e) => {
              e.stopPropagation();
              handleReplyLike(String(childReply.id));
            }}
            onReply={(e) => {
              e.stopPropagation();
              if (!authToken) {
                toast.info(t("COMMON.LOGIN_TO_REPLY"));
                return;
              }
              setReplyToId(String(childReply.id)); // Target this child reply
              setOpen(true);
            }}
          />
          {!!childReply.child_replies?.length && (
            <button type="button" onClick={openThisReply} className="col-start-2 mt-1 text-start text-xs font-bold text-[#65676B] hover:underline">
              {t("COMMON.VIEW_CHILD_REPLIES", { count: childReply.child_replies.length })}
            </button>
          )}
        </>
      ) : (
        <div className="mb-4">
          <p className="text-gray-500 italic text-base xs:text-xs xs:leading-[24px]">
            {t("COMMON.AUTHOR_DELETED_MESSAGE")}
          </p>
        </div>
      )}
    </div>
  );
}
