"use client";

import { useState } from "react";
import CommunityImageStrip from "./CommunityImageStrip";
import { type Reply } from "./UserReply";
import { useTranslation } from "react-i18next";
import { BsThreeDots } from "react-icons/bs";
import { MdEdit, MdDelete } from "react-icons/md";
import { useLanguageStore } from "@/store/languageStore";
import ReplyAuthorRow from "./ReplyAuthorRow";
import ReplyActionsRow from "./ReplyActionsRow";
import { pickLocalized } from "@/features/shared/types/cms";

interface ReplyItemProps {
  reply: Reply;
  index: number;
  totalSiblings: number;
  onLike: (replyId: string) => void;
  likeLoading: boolean;
  onEdit: (replyId: string) => void;
  onDelete: (replyId: string) => void;
  onReply: (replyId: string) => void;
  activeDropdown: string | null;
  setActiveDropdown: (id: string | null) => void;
  /*
   * The parent owns the map of open-dropdown elements; this registers one
   * entry into it. It takes a callback rather than the ref object itself
   * because a child writing into `props.someRef.current` is a mutation of
   * its own props — legal at runtime, but it hides who owns the map and the
   * React Compiler rejects it outright.
   */
  registerDropdown: (key: string, element: HTMLDivElement | null) => void;
  onNavigateToReply: (replyId: number) => void;
  onNavigateToProfile: (user: Reply["user"]) => void;
  onImageClick: (imageUrl: string) => void;
}

/**
 * One reply in a post's thread.
 *
 * Replies nest one level only: a reply to a reply is shown under its parent,
 * and anything deeper is reached through the reply's own page. That is why the
 * child count is rendered as a link rather than another level of this list.
 */
const ReplyItem = ({
  reply,
  onLike,
  onEdit,
  onDelete,
  onReply,
  activeDropdown,
  setActiveDropdown,
  registerDropdown,
  likeLoading,
  onNavigateToProfile,
  onImageClick,
}: ReplyItemProps) => {
  const { t } = useTranslation();
  const [expanded, setExpanded] = useState(false);
  const selectedLanguage = useLanguageStore((s) => s.language);

  // Count non-deleted child replies
  const childRepliesCount =
    reply.child_replies?.filter(
      (child) => !child.is_deleted || child.isPlaceholder
    ).length || 0;

  return (
    <div
      className="relative my-5 grid grid-cols-[40px_minmax(0,1fr)] items-start gap-x-2 sm:gap-x-3"
    >
      {/* Show dropdown only for non-placeholder and non-deleted replies */}
      {!reply.isPlaceholder && !reply.is_deleted && reply.is_creator && (
        <div
          className={`absolute z-10 top-0 ${
            selectedLanguage === "ar" ? "left-4" : "right-4"
          }`}
          ref={(el) => registerDropdown(`reply-${reply.id}`, el)}
        >
          <button
            onClick={() =>
              setActiveDropdown(
                activeDropdown === `reply-${reply.id}`
                  ? null
                  : `reply-${reply.id}`
              )
            }
            className="p-2 hover:bg-gray-100 rounded-full transition-colors duration-200"
          >
            <BsThreeDots className="text-primary-5 text-lg" />
          </button>

          {activeDropdown === `reply-${reply.id}` && (
            <div
              className={`absolute top-full mt-2 w-32 bg-white border border-gray-200 rounded-lg shadow-lg z-20 ${
                selectedLanguage === "ar" ? "left-0" : "right-0"
              }`}
            >
              <button
                onClick={() => onEdit(String(reply.id))}
                className="flex items-center gap-2 w-full px-4 py-2 text-left text-gray-700 hover:bg-gray-50 rounded-t-lg transition-colors duration-200"
              >
                <MdEdit className="text-primary-5" />
                <span className="text-sm">{t("COMMON.EDIT_TEXT")}</span>
              </button>
              <button
                onClick={() => onDelete(String(reply.id))}
                className="flex items-center gap-2 w-full px-4 py-2 text-left text-red-600 hover:bg-gray-50 rounded-b-lg transition-colors duration-200"
              >
                <MdDelete className="text-red-500" />
                <span className="text-sm">{t("COMMON.DELETE")}</span>
              </button>
            </div>
          )}
        </div>
      )}

      {/* Show profile section for non-placeholder replies */}
      {!reply.isPlaceholder ? (
        <ReplyAuthorRow
          reply={reply}
          selectedLanguage={selectedLanguage}
          onNavigateToProfile={onNavigateToProfile}
          onNavigateToReply={() => setExpanded(value => !value)}
        />
      ) : (
        <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>
      )}

      {/* Show content only for non-placeholder replies */}
      {!reply.isPlaceholder && (
        <>
          <div className="col-start-2 -mt-1 mb-1 min-w-0 rounded-b-2xl bg-[#F0F2F5] px-3 pb-3">
            <p className="whitespace-pre-wrap text-sm leading-relaxed text-[#303030] [overflow-wrap:anywhere] sm:text-base">
              {pickLocalized(reply.text_en, reply.text_ar, selectedLanguage)}
            </p>
          </div>

          {/* The shared strip: it filters the rows whose `image` is null
              (`next/image` throws on a missing `src`) and renders each
              thumbnail as a real button. No `stopPropagation` — the strip is a
              *sibling* of the text block that carries `onNavigateToReply`, so
              nothing above it listens. */}
          <div className="col-start-2 my-2 min-w-0"><CommunityImageStrip
            images={reply.reply_images}
            onImageClick={onImageClick}
            altPrefix="Reply"
          /></div>

          <ReplyActionsRow
            reply={reply}
            childRepliesCount={childRepliesCount}
            expanded={expanded}
            likeLoading={likeLoading}
            onLike={onLike}
            onReply={onReply}
            onNavigateToReply={() => setExpanded(value => !value)}
          />
        </>
      )}
      {reply.isPlaceholder && childRepliesCount > 0 && (
        <button type="button" className="col-span-2 text-start text-xs font-bold text-primary-5" onClick={() => setExpanded(value => !value)}>
          {t(expanded ? "COMMON.HIDE_CHILD_REPLIES" : "COMMON.VIEW_CHILD_REPLIES", { count: childRepliesCount })}
        </button>
      )}
      {expanded && childRepliesCount > 0 && (
        <div className="col-span-2 ms-4 min-w-0 border-s-2 border-[#E4E6EB] ps-2 sm:ms-8 sm:ps-3">
          {reply.child_replies.filter(child => !child.is_deleted || child.isPlaceholder).map((child, childIndex, siblings) => (
            <ReplyItem key={child.id} reply={child} index={childIndex} totalSiblings={siblings.length}
              onLike={onLike} likeLoading={likeLoading} onEdit={onEdit} onDelete={onDelete}
              onReply={onReply} activeDropdown={activeDropdown} setActiveDropdown={setActiveDropdown}
              registerDropdown={registerDropdown} onNavigateToReply={() => {}}
              onNavigateToProfile={onNavigateToProfile} onImageClick={onImageClick} />
          ))}
        </div>
      )}
    </div>
  );
};

export default ReplyItem;
