"use client";

import { asReplyViews } from "@/features/community/communityRecord";
import { useCallback, 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 UserReplyProps } from "./UserReply";
import {
  getApiErrorMessage,
  getApiErrorMessages,
  getLocalizedApiMessage,
} from "@/lib/api/errors";

/**
 * A post's replies: the paged list, the optimistic like, and delete.
 */
export function useUserReply({
  isReplyCreated,
  postId,
  onReplyDeleted,
}: UserReplyProps) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const router = useRouter();
  const authToken = useAuthStore((s) => s.user?.auth_token);

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

  const [isNewReplyCreated, setIsNewReplyCreated] = useState(false);
  const [openReplyForm, setOpenReplyForm] = useState(false);
  const [openCreateReplyOfReplyForm, setOpenCreateReplyOfReplyForm] =
    useState(false);
  const [openConfirmModal, setOpenConfirmModal] = useState(false);
  const [openDeleteConfirmModal, setOpenDeleteConfirmModal] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [replyId, setReplyId] = useState("");
  const [activeDropdown, setActiveDropdown] = useState<string | null>(null);
  const [localRepliesData, setLocalRepliesData] = useState<Reply[]>([]);
  const dropdownRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
  const formRef = useRef<HTMLFormElement | null>(null);

  /*
   * Deletes on unmount rather than storing null. The map is only ever read by
   * the click-outside handler below, and an entry left behind points at a
   * detached node forever — harmless per click, but the map grew for the
   * lifetime of the page as replies paged in and out.
   */
  const registerDropdown = useCallback(
    (key: string, element: HTMLDivElement | null) => {
      setDropdownRef(dropdownRefs.current, key, element);
    },
    []
  );
  const validateFormRef = useRef<(() => Promise<boolean>) | null>(null);

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

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

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

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

  /*
   * The reply list, 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 data>(undefined);
  if (data !== seededResponse) {
    setSeededResponse(data);
    /* `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(data)) {
      repliesData = asReplyViews(data);
    } else if (Array.isArray(data?.data)) {
      repliesData = asReplyViews(data.data);
    }
    setLocalRepliesData(repliesData);
  }

  // Only show top-level replies (no nesting)
  const topLevelReplies = localRepliesData.filter(
    (reply) => !reply.is_deleted || reply.isPlaceholder
  );

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

    // Optimistic update - immediately update local state
    const previousData = [...localRepliesData];
    setLocalRepliesData((prevReplies) =>
      prevReplies.map((reply) =>
        String(reply.id) === targetReplyId
          ? {
              ...reply,
              is_liked: !reply.is_liked,
              likes_count: reply.is_liked
                ? reply.likes_count - 1
                : reply.likes_count + 1,
            }
          : reply
      )
    );

    try {
      await likeMutation.mutateAsync({ reply_id: targetReplyId });
      // 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 = (targetReplyId: string) => {
    setReplyId(targetReplyId);
    setActiveDropdown(null);
    setOpenReplyForm(true);
  };

  const handleDelete = (targetReplyId: string) => {
    setReplyId(targetReplyId);
    setActiveDropdown(null);
    setOpenDeleteConfirmModal(true);
  };

  const handleConfirmDelete = async () => {
    try {
      await deleteMutation.mutateAsync(replyId);
      toast.success(t("COMMON.REPLY_DELETED_SUCCESSFULLY"));
      setOpenDeleteConfirmModal(false);
      refetch();
      onReplyDeleted?.(); // Trigger post refetch
    } 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 (replyId) {
      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 handleReply = (targetReplyId: string) => {
    if (!authToken) {
      toast.info(t("COMMON.LOGIN_TO_REPLY"));
      return;
    }
    setReplyId(targetReplyId);
    setOpenCreateReplyOfReplyForm(true);
  };

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

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

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

  return {
    repliesLoading,
    /** A failed load is not "no replies" (p.37). */
    repliesError: repliesFailed ? repliesError : null,
    refetch,
    selectedLanguage,
    router,
    authToken,
    likeMutation,
    deleteMutation,
    isNewReplyCreated,
    setIsNewReplyCreated,
    openReplyForm,
    setOpenReplyForm,
    openCreateReplyOfReplyForm,
    setOpenCreateReplyOfReplyForm,
    openConfirmModal,
    setOpenConfirmModal,
    openDeleteConfirmModal,
    setOpenDeleteConfirmModal,
    isSubmitting,
    setIsSubmitting,
    replyId,
    setReplyId,
    activeDropdown,
    setActiveDropdown,
    localRepliesData,
    setLocalRepliesData,
    dropdownRefs,
    formRef,
    registerDropdown,
    validateFormRef,
    topLevelReplies,
    handleReplyLike,
    handleEdit,
    handleDelete,
    handleConfirmDelete,
    handleSaveClick,
    handleConfirmUpdate,
    handleReply,
    handleNavigateToReply,
    handleNavigateToProfile,
    handleImageClick,
  };
}
