"use client";

import { asReplyViews } from "@/features/community/communityRecord";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { deleteReply, getCommunityReplies, likeCommunityPost } from "@/features/community/services/communityApi";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import {
  isClickOutsideDropdowns,
  setDropdownRef,
} from "./dropdownRefs";

import {
  type Reply,
  type ReplyDetailPageProps,
} from "./replyDetailTypes";
import {
  getApiErrorMessage,
  getApiErrorMessages,
  getLocalizedApiMessage,
} from "@/lib/api/errors";

/**
 * One reply's own page: the reply, its children, and the like/delete actions.
 */
export function useReplyDetail({ postId, replyId }: ReplyDetailPageProps) {
  const [open, setOpen] = useState(false);
  const { t } = useTranslation();
  const router = useRouter();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const authToken = useAuthStore((s) => s.user?.auth_token);

  const likeMutation = useMutation({ mutationFn: likeCommunityPost });
  const deleteMutation = useMutation({ mutationFn: deleteReply });

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isReplyCreated, setIsReplyCreated] = useState(false);
  const [showDropdown, setShowDropdown] = useState<string | null>(null);
  const [openEditReplyModal, setOpenEditReplyModal] = useState(false);
  const [openConfirmModal, setOpenConfirmModal] = useState(false);
  const [openDeleteConfirmModal, setOpenDeleteConfirmModal] = useState(false);
  const [selectedReplyId, setSelectedReplyId] = useState("");
  const [replyToId, setReplyToId] = useState(""); // Track which reply we're replying to
  const [localRepliesData, setLocalRepliesData] = useState<Reply[]>([]);
  const validateFormRef = useRef<(() => Promise<boolean>) | null>(null);
  const formRef = useRef<HTMLFormElement | null>(null);
  const dropdownRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});

  /**
   * Registers the element a dropdown is anchored to, so the click-outside
   * handler below can tell a click on the open menu from a click away from it.
   *
   * It is a callback rather than the ref object itself because the page and
   * every reply under it share one map, and writing into a hook's ref from the
   * component that renders it is what `react-hooks/immutability` flags.
   */
  const registerDropdownRef =
    (key: string) => (el: HTMLDivElement | null) => {
      setDropdownRef(dropdownRefs.current, key, el);
    };

  const {
    data: apiResponse,
    isLoading,
    isError,
    error,
    refetch,
  } = useQuery({
    queryKey: ["community-replies", String(postId)],
    queryFn: () => getCommunityReplies(String(postId)),
    enabled: Boolean(postId),
  });

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const clickedOutside = isClickOutsideDropdowns(
        dropdownRefs.current,
        event.target as Node
      );
      if (clickedOutside) {
        setShowDropdown(null);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  /*
   * The reply tree, with the reader's own un-acknowledged changes applied.
   *
   * This is a genuine local override of server data — the like / delete
   * handlers below write it optimistically and roll it back on failure — so it
   * cannot be derived away. What it does not need is an effect: React's
   * adjust-on-change pattern re-seeds it in the render that first sees a new
   * response, keyed on the response's identity exactly as the effect's
   * dependency list was.
   *
   * The frame the effect used to cost is visible here: an optimistic like that
   * failed rolled the count back, then the refetch painted the stale server
   * count for one more frame before the effect overwrote it.
   */
  const [seededResponse, setSeededResponse] =
    useState<typeof apiResponse>(undefined);
  if (apiResponse !== seededResponse) {
    setSeededResponse(apiResponse);
    /* `asReplyViews` rather than a direct assignment: the view type narrows
       `user` to non-null and the payload type does not. */
    let repliesData: Reply[] = [];
    if (Array.isArray(apiResponse)) {
      repliesData = asReplyViews(apiResponse);
    } else if (Array.isArray(apiResponse?.data)) {
      repliesData = asReplyViews(apiResponse.data);
    }
    setLocalRepliesData(repliesData);
  }

  useEffect(() => {
    refetch();
  }, [authToken, isReplyCreated, refetch]);

  // Find the target reply and its children
  const findReply = (replies: Reply[], targetId: string): Reply | null => {
    for (const reply of replies) {
      if (String(reply.id) === targetId) {
        return reply;
      }
      if (reply.child_replies && reply.child_replies.length > 0) {
        const found = findReply(reply.child_replies, targetId);
        if (found) return found;
      }
    }
    return null;
  };

  /* `String(...)` because `findReply` matches on a string id, and `replyId`
     is a number when the caller passes it from the payload. */
  const targetReply = findReply(localRepliesData, replyId ? String(replyId) : "");

  // A reply that isn't in the tree means a stale link — go back. A failed
  // load proves nothing about the link: it shows an error with retry instead.
  useEffect(() => {
    if (!isLoading && !isError && (!postId || !replyId || !targetReply)) {
      router.back();
    }
  }, [isLoading, isError, postId, replyId, targetReply, router]);

  const handleReplyLike = async (likeReplyId: string) => {
    if (!authToken) {
      toast.info(t("COMMON.LOGIN_TO_LIKE"));
      return;
    }

    // Optimistic update - immediately update local state
    const previousData = [...localRepliesData];
    const updateReplyInTree = (replies: Reply[]): Reply[] =>
      replies.map((reply) => {
        if (String(reply.id) === likeReplyId) {
          return {
            ...reply,
            is_liked: !reply.is_liked,
            likes_count: reply.is_liked
              ? reply.likes_count - 1
              : reply.likes_count + 1,
          };
        }
        if (reply.child_replies && reply.child_replies.length > 0) {
          return {
            ...reply,
            child_replies: updateReplyInTree(reply.child_replies),
          };
        }
        return reply;
      });
    setLocalRepliesData((prevReplies) => updateReplyInTree(prevReplies));

    try {
      await likeMutation.mutateAsync({ reply_id: likeReplyId });
      // Refetch in background to sync with server
      refetch();
    } catch (error) {
      // Revert optimistic update on error
      setLocalRepliesData(previousData);
      console.error("Like failed:", error);
      toast.error(getApiErrorMessage(error, selectedLanguage, t("COMMON.LIKE_FAILED")));
    }
  };

  const handleEdit = (editReplyId: string) => {
    setSelectedReplyId(editReplyId);
    setShowDropdown(null);
    setOpenEditReplyModal(true);
  };

  const handleDelete = (deleteReplyId: string) => {
    setSelectedReplyId(deleteReplyId);
    setShowDropdown(null);
    setOpenDeleteConfirmModal(true);
  };

  const handleImageClick = (imageUrl: string) => {
    // Open the image in a new tab/window
    window.open(imageUrl, "_blank");
  };

  const navigateToProfile = (user: Reply["user"]) => {
    router.push(
      `/public-profile/${user.id}`
    );
  };

  const handleConfirmDelete = async () => {
    try {
      await deleteMutation.mutateAsync(selectedReplyId);
      toast.success(t("COMMON.REPLY_DELETED_SUCCESSFULLY"));
      setOpenDeleteConfirmModal(false);
      refetch();
      // Navigate back if deleting the main reply
      if (selectedReplyId === replyId) {
        router.back();
      }
    } catch (err) {
      /* Both envelope shapes, and the localized pair, are handled by
         `lib/api/errors.ts`; this block used to re-implement the
         legacy `errors[field][lang]` walk by hand. */
      const messages = getApiErrorMessages(err, selectedLanguage);
      if (messages.length > 0) {
        messages.forEach((message) => toast.error(message));
      } else {
        toast.error(
          getLocalizedApiMessage(err, selectedLanguage, t("COMMON.DELETE_REPLY_FAILED"))
        );
      }
    }
  };

  const handleSaveClick = async (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (selectedReplyId) {
      if (validateFormRef.current) {
        const isValid = await validateFormRef.current();
        if (isValid) {
          setOpenConfirmModal(true);
        }
      }
    } else if (formRef.current) {
      formRef.current.requestSubmit();
    }
  };

  const handleConfirmUpdate = () => {
    if (formRef.current) {
      formRef.current.requestSubmit();
    }
    setOpenConfirmModal(false);
  };

  const handleNavigateToReply = (childReplyId: number) => {
    router.push(`/community/${postId}/reply/${childReplyId}`);
  };

  return {
    refetch,
    isLoading,
    loadError: isError ? error : null,
    open,
    setOpen,
    router,
    selectedLanguage,
    authToken,
    likeMutation,
    deleteMutation,
    isSubmitting,
    setIsSubmitting,
    isReplyCreated,
    setIsReplyCreated,
    showDropdown,
    setShowDropdown,
    openEditReplyModal,
    setOpenEditReplyModal,
    openConfirmModal,
    setOpenConfirmModal,
    openDeleteConfirmModal,
    setOpenDeleteConfirmModal,
    selectedReplyId,
    setSelectedReplyId,
    replyToId,
    setReplyToId,
    localRepliesData,
    setLocalRepliesData,
    validateFormRef,
    formRef,
    dropdownRefs,
    registerDropdownRef,
    findReply,
    targetReply,
    handleReplyLike,
    handleEdit,
    handleDelete,
    handleImageClick,
    navigateToProfile,
    handleConfirmDelete,
    handleSaveClick,
    handleConfirmUpdate,
    handleNavigateToReply,
  };
}
