"use client";

import useAxios from "@/hooks/useAxios";
import Image from "next/image";
import React, { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import BillboardCommentsModal from "./BillboardCommentsModal";
import { SocialStatButton } from "@/components/ui/SocialStatButton";
import { cn } from "@/lib/utils";

function MainBillboardCardActions({
  _id,
  likedByUser,
  likesCount: lCount,
  viewCount: initialViewCount,
  commentsCount,
  trackView = false,
  showViewCount = true,
}: {
  _id: string;
  likedByUser: boolean | null;
  likesCount: number;
  viewCount: number;
  commentsCount: number;
  /** ثبت بازدید فقط هنگام باز کردن صفحه جزئیات */
  trackView?: boolean;
  /** در لیست: نمایش تعداد بازدید بدون ثبت بازدید جدید */
  showViewCount?: boolean;
}) {
  const { t } = useTranslation("common");
  const [showCommentsModal, setShowCommentsModal] = useState<boolean>(false);
  const [liked, setLiked] = useState<boolean | null>(likedByUser);
  const [likesCount, setLikesCount] = useState<number>(lCount ?? 0);
  const [viewCount, setViewCount] = useState<number>(initialViewCount ?? 0);
  const viewRecordedRef = useRef(false);
  const { request, loading } = useAxios();

  useEffect(() => {
    setLiked(likedByUser);
    setLikesCount(lCount ?? 0);
  }, [likedByUser, lCount]);

  useEffect(() => {
    setViewCount(initialViewCount ?? 0);
  }, [initialViewCount]);

  useEffect(() => {
    if (!trackView || !_id || viewRecordedRef.current) return;

    const storageKey = `billboard-view-${_id}`;
    if (typeof window !== "undefined") {
      if (sessionStorage.getItem(storageKey)) return;
      sessionStorage.setItem(storageKey, "1");
    }

    viewRecordedRef.current = true;

    void (async () => {
      try {
        const response = await request<{ viewCount?: number }>(
          "POST",
          `/advertising/view/${_id}`,
          null,
          { noToast: true }
        );
        if (typeof response?.viewCount === "number") {
          setViewCount(response.viewCount);
        } else {
          setViewCount((prev) => prev + 1);
        }
      } catch (error) {
        viewRecordedRef.current = false;
        if (typeof window !== "undefined") {
          sessionStorage.removeItem(storageKey);
        }
        console.log(error);
      }
    })();
  }, [_id, trackView, request]);

  const toggleLike = async () => {
    if (loading) return;
    const newLiked = !liked;
    const newLikesCount = newLiked
      ? Number(likesCount) + 1
      : Number(likesCount) - 1;

    setLiked(newLiked);
    setLikesCount(newLikesCount);

    try {
      await request(
        "POST",
        "/advertising/like",
        {
          advertisingId: _id,
        },
        { noToast: true }
      );
    } catch (error: unknown) {
      console.log(error);
      setLiked(!newLiked);
      setLikesCount(likesCount);
    }
  };

  return (
    <div
      className={cn(
        "mt-4 flex w-full flex-row items-center gap-6",
        showViewCount ? "max-w-none pr-3" : "max-w-[140px]"
      )}
      onClick={(e) => e.stopPropagation()}
    >
      {showCommentsModal && (
        <BillboardCommentsModal
          isOpen={showCommentsModal}
          onClose={() => setShowCommentsModal(false)}
          advertisingId={_id}
        />
      )}
      <SocialStatButton
        layout="horizontal"
        likeCount={likesCount}
        onClick={(e) => {
          e.stopPropagation();
          void toggleLike();
        }}
        aria-label={t("billboards.actions.like")}
        icon={
          <Image
            width={20}
            height={20}
            alt=""
            src={
              !liked ? `/images/icons/heart.svg` : `/images/icons/red-heart.svg`
            }
            className={!liked ? `dark:invert` : ""}
          />
        }
      />
      <SocialStatButton
        layout="horizontal"
        count={commentsCount}
        onClick={(e) => {
          e.stopPropagation();
          setShowCommentsModal(!showCommentsModal);
        }}
        aria-label={t("billboards.actions.comment")}
        icon={
          <Image
            width={20}
            height={20}
            alt=""
            src={`/images/icons/message-text.svg`}
            className="dark:invert"
          />
        }
      />
      {showViewCount ? (
        <SocialStatButton
          layout="horizontal"
          count={viewCount}
          showZero
          aria-label={t("billboards.actions.view")}
          className="pointer-events-none"
          icon={
            <Image
              width={20}
              height={20}
              alt=""
              src={`/images/icons/eye.svg`}
              className="dark:invert"
            />
          }
        />
      ) : null}
    </div>
  );
}

export default MainBillboardCardActions;
