"use client";

import { communityTagHref } from "@/features/community/communityTag";
import React, { useState, useRef, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { useMutation } from "@tanstack/react-query";
import { useLanguageStore } from "@/store/languageStore";
import { useAuthStore } from "@/store/authStore";
import { likeCommunityPost, deleteCommunityPost } from "@/features/community/services/communityApi";

import { type PostData } from "./InnerPost";
import {
  getApiErrorMessage,
  getApiErrorMessages,
  getLocalizedApiMessage,
} from "@/lib/api/errors";

/**
 * A post card's state: the optimistic like, the owner menu, and the reply and
 * edit dialogs.
 */
export function useInnerPost({ data, refetch }: PostData) {
  const [open, setOpen] = useState(false);
  const [openReplyForm, setOpenReplyForm] = useState(false);
  const [opencreatepost, setcreatepost] = useState(false);
  const [showDropdown, setShowDropdown] = useState(false);
  const [openConfirmModal, setOpenConfirmModal] = useState(false);
  const [openDeleteConfirmModal, setOpenDeleteConfirmModal] = useState(false);
  /* Derived, not stored: nothing but the removed effect ever set this, so the
     state only served to make the correct value arrive one commit late. */
  const state = data?.proposing_idea ? 2 : 1;
  const [localPostData, setLocalPostData] = useState(data);

  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const router = useRouter();
  const user = useAuthStore((s) => s.user);
  const authToken = user?.auth_token;

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isPostSubmitting, setIsPostSubmitting] = useState(false);
  const [isSubmittingReply, setIsSubmittingReply] = useState(false);

  // Mutations
  const likePostMutation = useMutation({
    mutationFn: likeCommunityPost,
  });

  const deletePostMutation = useMutation({
    mutationFn: deleteCommunityPost,
  });

  const dropdownRef = useRef<HTMLDivElement>(null);
  const formRef = useRef<HTMLFormElement | null>(null);
  const validateFormRef = useRef<(() => Promise<boolean>) | null>(null);

  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);
    };
  }, []);

  /*
   * Follow the query data during render, not from an effect.
   *
   * `localPostData` is written optimistically by the like handler and rolled
   * back on failure, so it cannot simply be derived — but it must re-sync when
   * a refetch brings new data. The effect version showed the previous post for
   * one frame after every refetch.
   */
  const [prevData, setPrevData] = useState(data);
  if (data !== prevData) {
    setPrevData(data);
    setLocalPostData(data);
  }

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

    const previousData = localPostData;
    setLocalPostData((prev) => ({
      ...prev,
      is_liked: !prev.is_liked,
      likes_count: prev.is_liked ? prev.likes_count - 1 : prev.likes_count + 1,
    }));

    try {
      /* The toggle answers with the resulting state; take it rather than
         refetching — `refetch` is the list's reload, which returns the feed to
         page 1. */
      const response = await likePostMutation.mutateAsync({ post_id: postId });
      if (response?.data) {
        setLocalPostData((prev) => ({
          ...prev,
          is_liked: Boolean(response.data.is_liked),
          likes_count: Number(response.data.likes_count),
        }));
      }
    } catch (likeError) {
      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 handleConfirmDelete = async () => {
    try {
      await deletePostMutation.mutateAsync(String(data?.id));
      toast.success(t("COMMON.TOAST.POST_DELETED_SUCCESSFULLY"));
      setOpenDeleteConfirmModal(false);
      refetch?.();
    } catch (err) {
      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 (data?.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);
  };

  /** A reply was posted from the card: count it here instead of reloading the list. */
  const handleReplyCreated = () =>
    setLocalPostData((prev) => ({ ...prev, replies_count: (prev.replies_count ?? 0) + 1 }));

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

  return {
    open,
    setOpen,
    openReplyForm,
    setOpenReplyForm,
    opencreatepost,
    setcreatepost,
    showDropdown,
    setShowDropdown,
    openConfirmModal,
    setOpenConfirmModal,
    openDeleteConfirmModal,
    setOpenDeleteConfirmModal,
    state,
    localPostData,
    setLocalPostData,
    selectedLanguage,
    router,
    user,
    authToken,
    isSubmitting,
    setIsSubmitting,
    isPostSubmitting,
    setIsPostSubmitting,
    isSubmittingReply,
    setIsSubmittingReply,
    likePostMutation,
    deletePostMutation,
    dropdownRef,
    formRef,
    validateFormRef,
    handlePostLike,
    handleEdit,
    handleDelete,
    handleConfirmDelete,
    handleSaveClick,
    handleConfirmUpdate,
    handleTagClick,
    handleReplyCreated,
  };
}
