"use client";

import { communityTagHref } from "@/features/community/communityTag";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { invalidateCommunityFeeds } from "@/features/community/communityQueryKeys";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { deleteCommunityPost, getCommunityPostById, likeCommunityPost } from "@/features/community/services/communityApi";
import { useAuthStore } from "@/store/authStore";
import { useSessionReady } from "@/store/useSessionReady";
import { useLanguageStore } from "@/store/languageStore";
import { PostData } from "./InnerPost";
import {
  getApiErrorMessage,
  getApiErrorMessages,
  getLocalizedApiMessage,
} from "@/lib/api/errors";

/**
 * A single community post: the post itself, its replies, and the like/delete
 * actions.
 */
export function useCommunityDetail(id: string) {
  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 sessionReady = useSessionReady();

  const likeMutation = useMutation({ mutationFn: likeCommunityPost });
  const queryClient = useQueryClient();
  // The feed this page redirects to must not still show the deleted post.
  const deleteMutation = useMutation({ mutationFn: deleteCommunityPost, onSuccess: () => invalidateCommunityFeeds(queryClient) });

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isReplyCreated, setIsReplyCreated] = useState(false);
  const [showDropdown, setShowDropdown] = useState(false);
  const [opencreatepost, setcreatepost] = useState(false);
  const [openDeleteConfirmModal, setOpenDeleteConfirmModal] = useState(false);
  const [isPostSubmitting, setIsPostSubmitting] = useState(false);
  const [openConfirmModal, setOpenConfirmModal] = useState(false);
  const [localPostData, setLocalPostData] = useState<PostData["data"] | null>(
    null
  );
  const validateFormRef = useRef<(() => Promise<boolean>) | null>(null);
  const formRef = useRef<HTMLFormElement | null>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const {
    data: apiResponse,
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ["community-post", id, Boolean(authToken)],
    queryFn: () => getCommunityPostById(id),
    /*
     * `sessionReady` as well as the id: the token is part of the key, and on
     * the client the first render deliberately works from the signed-out
     * server snapshot (see `useSessionReady`). Without this the query would
     * fire once keyed `false` and again keyed `true`, so every signed-in
     * reader of this screen would cost two requests instead of one. The wait
     * is a single render, before paint, not a round trip.
     */
    enabled: sessionReady && Boolean(id),
  });

  const postData: PostData["data"] | undefined = Array.isArray(apiResponse?.data)
    ? apiResponse?.data[0]
    : apiResponse?.data;

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setShowDropdown(false);
      }
    };

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

  /*
   * The post, 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 [seededPost, setSeededPost] = useState<typeof postData>(undefined);
  if (postData && postData !== seededPost) {
    setSeededPost(postData);
    setLocalPostData(postData);
  }

  /* A missing or deleted post (404) or a failed read now renders an
     unavailable state on this page (`CommunityLoadError`) instead of silently
     replacing the URL with the homepage. */

  const handlePostLike = async (postId: string) => {
    if (!authToken) {
      toast.info(t("COMMON.LOGIN_TO_LIKE_POST"));
      return;
    }

    // Optimistic update - immediately update local state
    const previousData = localPostData;
    setLocalPostData((prev) =>
      prev
        ? {
            ...prev,
            is_liked: !prev.is_liked,
            likes_count: prev.is_liked
              ? prev.likes_count - 1
              : prev.likes_count + 1,
          }
        : prev
    );

    try {
      await likeMutation.mutateAsync({ post_id: postId });
      // Refetch in background to sync with server
      refetch();
    } catch (likeError) {
      // Revert optimistic update on error
      setLocalPostData(previousData);
      toast.error(getApiErrorMessage(likeError, selectedLanguage, t("COMMON.LIKE_FAILED")));
    }
  };

  const handleEdit = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setShowDropdown(false);
    setcreatepost(true);
  };

  const handleDelete = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setShowDropdown(false);
    setOpenDeleteConfirmModal(true);
  };

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

  // Handle tag click
  const handleTagClick = (tag: string) => {
    // Encoded because Arabic hashtags are the common case here.
    router.push(communityTagHref(tag));
  };

  const handleConfirmDelete = async () => {
    try {
      await deleteMutation.mutateAsync(String(postData!.id));
      toast.success(t("COMMON.TOAST.POST_DELETED_SUCCESSFULLY"));
      setOpenDeleteConfirmModal(false);
      router.push("/community"); // Redirect to community page after deletion
    } 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.TOAST.DELETE_POST_FAILED"))
        );
      }
    }
  };

  const handleSaveClick = async (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (postData?.id) {
      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 postUser = postData?.user;
  // `"/"` when there is no user at all, so the avatar is never a dead link.
  const profileUrl = postUser ? `/public-profile/${postUser.id}` : "/";

  return {
    postUser,
    profileUrl,
    isLoading: isLoading || !sessionReady,
    error,
    refetch,
    open,
    setOpen,
    router,
    selectedLanguage,
    authToken,
    likeMutation,
    deleteMutation,
    isSubmitting,
    setIsSubmitting,
    isReplyCreated,
    setIsReplyCreated,
    showDropdown,
    setShowDropdown,
    opencreatepost,
    setcreatepost,
    openDeleteConfirmModal,
    setOpenDeleteConfirmModal,
    isPostSubmitting,
    setIsPostSubmitting,
    openConfirmModal,
    setOpenConfirmModal,
    localPostData,
    setLocalPostData,
    validateFormRef,
    formRef,
    dropdownRef,
    postData,
    handlePostLike,
    handleEdit,
    handleDelete,
    handleImageClick,
    handleTagClick,
    handleConfirmDelete,
    handleSaveClick,
    handleConfirmUpdate,
  };
}
