"use client";

import { Post } from "@/types/types";
import Image from "next/image";
import React, { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import ReportModal from "@/components/main/ReportModal";
import CommentsModal from "@/components/models/MainModelCard/CommentsModal";
import useAxios from "@/hooks/useAxios";
import toast from "react-hot-toast";
import ModelDetailModal from "@/components/models/ModelDetailModal";
import ModelServiceModal from "@/components/models/ModelServiceModal";
import { useUserById } from "@/hooks/getUserById";
import { AxiosError } from "axios";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import SharePostModal from "@/components/main/SharePostModal";
import BoldIcon from "@/components/ui/BoldIcon";
import Cookies from "js-cookie";
import { trackExploreInteraction } from "@/api/trackExploreInteraction";
import { useRequireAuth } from "@/lib/auth/useRequireAuth";

interface ReelsPostActionsProps {
  postData: Post;
}

export default function ReelsPostActions({ postData }: ReelsPostActionsProps) {
  const {
    _id: postId,
    user_id,
    user_name,
    likesCount,
    is_liked,
    type: postType,
  } = postData;

  const user = useUserById(user_id);
  const expertise = user?.expertise;
  const hair_color = user?.hair_color;
  const eye_color = user?.eye_color;
  const height = user?.height;
  const size = user?.size;
  const weight = user?.weight;
  const services = user?.services;

  const [expanded, setExpanded] = useState(false);
  const [showReportModal, setShowReportModal] = useState(false);
  const [showCommentsModal, setShowCommentsModal] = useState(false);
  const [showShareModal, setShowShareModal] = useState(false);
  const [showServicesModal, setShowServicesModal] = useState(false);
  const [liked, setLiked] = useState<boolean>(is_liked || false);
  const [likesCountState, setLikesCount] = useState<number>(likesCount || 0);

  const { request, loading } = useAxios();
  const requireAuth = useRequireAuth();

  const toggleLike = async () => {
    if (!requireAuth()) return;
    if (!user_id || !postId) {
      toast.error("لطفاً وارد حساب کاربری خود شوید یا ثبت‌نام کنید");
      return;
    }
    if (loading) return;

    const newLiked = !liked;
    const newLikesCount = newLiked ? likesCountState + 1 : likesCountState - 1;
    setLiked(newLiked);
    setLikesCount(newLikesCount);

    try {
      const response = await request<{ likesCount?: number; is_liked?: boolean }>(
        "POST",
        "/posts/like",
        { postId },
        { noToast: true }
      );
      setLikesCount(response?.likesCount ?? newLikesCount);
      setLiked(response?.is_liked ?? newLiked);

      const token = Cookies.get("token") || "";
      if (token && newLiked) {
        trackExploreInteraction(
          {
            targetType: "post",
            targetId: postId,
            authorId: user_id,
            contentType: postType === "video" ? "video" : "image",
            action: "like",
          },
          token
        );
      }
    } catch (error: unknown) {
      let errorMessage = "خطا در ارتباط با سرور";
      if (error instanceof Error) errorMessage = error.message;
      else if (error instanceof AxiosError)
        errorMessage = error.response?.data?.message ?? error.message;
      toast.error(errorMessage);
      setLiked(!newLiked);
      setLikesCount(likesCountState);
    }
  };

  const shareUrl = postId
    ? `https://modstagram.com/posts/${postId}`
    : user_name
      ? `https://modstagram.com/users/${user_name}`
      : "";

  const { data } = useInfiniteScroll({
    endpoint: "/users/comments",
    queryKey: ["comments", user_id, postId || "all"],
    params: postId
      ? { user_id, post_id: postId }
      : { user_id },
  });

  const commentCount =
    data?.pages
      ?.flatMap((p) => p?.comments || [])
      .filter((c: { post_id?: string; postId?: string }) =>
        postId
          ? c.post_id === postId || c.postId === postId || (!c.post_id && !c.postId)
          : true
      ).length ?? 0;

  const actionButtonClass =
    "flex flex-col items-center gap-1 text-white drop-shadow-md";

  return (
    <>
      {showReportModal && (
        <ReportModal
          isOpen={showReportModal}
          onClose={() => setShowReportModal(false)}
        />
      )}
      {showCommentsModal && (
        <CommentsModal
          isOpen={showCommentsModal}
          onClose={() => setShowCommentsModal(false)}
          userId={user_id}
          postId={postId}
        />
      )}
      <SharePostModal
        open={showShareModal}
        onClose={() => setShowShareModal(false)}
        url={shareUrl}
      />
      {showServicesModal &&
        (expertise === "مدلینگ" ? (
          <ModelDetailModal
            hairColor={hair_color}
            eyeColor={eye_color}
            height={height}
            size={size}
            weight={weight}
            isOpen={showServicesModal}
            onClose={() => setShowServicesModal(false)}
            isMain
            userId={user_id}
          />
        ) : (
          <ModelServiceModal
            services={services}
            isOpen={showServicesModal}
            onClose={() => setShowServicesModal(false)}
            userId={user_id}
          />
        ))}

      <div className="absolute left-3 bottom-36 z-30 flex flex-col items-center">
        <AnimatePresence mode="wait">
          {!expanded ? (
            <motion.button
              key="trigger"
              type="button"
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.8 }}
              transition={{ duration: 0.2 }}
              onClick={() => setExpanded(true)}
              className="flex h-11 w-11 items-center justify-center rounded-full bg-black/40 backdrop-blur-md"
              aria-label="نمایش عملیات"
            >
              <BoldIcon name="grid-3" size={24} className="block dark:invert" />
            </motion.button>
          ) : (
            <motion.div
              key="actions"
              initial={{ opacity: 0, y: 12 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: 12 }}
              transition={{ duration: 0.25, ease: "easeOut" }}
              className="flex flex-col items-center gap-5"
            >
              <button
                type="button"
                onClick={toggleLike}
                className={actionButtonClass}
                aria-label="لایک"
              >
                <Image
                  width={28}
                  height={28}
                  alt="heart"
                  src={liked ? "/images/icons/red-heart.svg" : "/images/icons/heart.svg"}
                  className="drop-shadow-lg"
                />
                <span className="text-xs font-semibold">{likesCountState}</span>
              </button>
              <button
                type="button"
                onClick={() => setShowCommentsModal(true)}
                className={actionButtonClass}
                aria-label="کامنت"
              >
                <Image
                  width={28}
                  height={28}
                  alt="comment"
                  src="/images/icons/message-text.svg"
                  className="invert drop-shadow-lg"
                />
                <span className="text-xs font-semibold">{commentCount}</span>
              </button>
              <button
                type="button"
                onClick={() => {
                  if (shareUrl) {
                    const token = Cookies.get("token") || "";
                    if (token) {
                      trackExploreInteraction(
                        {
                          targetType: "post",
                          targetId: postId,
                          authorId: user_id,
                          contentType: postType === "video" ? "video" : "image",
                          action: "share",
                        },
                        token
                      );
                    }
                    setShowShareModal(true);
                  }
                }}
                className={actionButtonClass}
                aria-label="اشتراک‌گذاری"
              >
                <Image
                  width={28}
                  height={28}
                  alt="share"
                  src="/images/icons/share.svg"
                  className="invert drop-shadow-lg"
                />
              </button>
              <button
                type="button"
                onClick={() => setExpanded(false)}
                className="mt-1 flex h-9 w-9 items-center justify-center rounded-full bg-black/40 backdrop-blur-md"
                aria-label="بستن"
              >
                <BoldIcon name="close-circle" size={20} tinted className="text-white" />
              </button>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </>
  );
}

/** دکمه درخواست همکاری برای نوار پایین */
export function ReelsCollaborationButton({
  postData,
}: {
  postData: Post;
}) {
  const user = useUserById(postData.user_id);
  const [showServicesModal, setShowServicesModal] = useState(false);

  return (
    <>
      {showServicesModal &&
        (user?.expertise === "مدلینگ" ? (
          <ModelDetailModal
            hairColor={user?.hair_color}
            eyeColor={user?.eye_color}
            height={user?.height}
            size={user?.size}
            weight={user?.weight}
            isOpen={showServicesModal}
            onClose={() => setShowServicesModal(false)}
            isMain
            userId={postData.user_id}
          />
        ) : (
          <ModelServiceModal
            services={user?.services}
            isOpen={showServicesModal}
            onClose={() => setShowServicesModal(false)}
            userId={postData.user_id}
          />
        ))}
      <button
        type="button"
        onClick={() => setShowServicesModal(true)}
        className="shrink-0 rounded-lg border border-white/80 px-3 py-1.5 text-xs font-semibold text-white backdrop-blur-sm transition active:scale-95"
      >
        درخواست همکاری
      </button>
    </>
  );
}
