"use client";

import { Post } from "@/types/types";
import Image from "next/image";
import React, { useState } from "react";
import ReportModal from "../../main/ReportModal";
import CommentsModal from "./CommentsModal";
import useAxios from "@/hooks/useAxios";
import toast from "react-hot-toast";
import RoundedButton from "@/components/elements/RoundedButton";
import ModelDetailModal from "../ModelDetailModal";
import ModelServiceModal from "../ModelServiceModal";
import { useUserById } from "@/hooks/getUserById";
import { AxiosError } from "axios";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import SharePostModal from "@/components/main/SharePostModal";
import { useRequireAuth } from "@/lib/auth/useRequireAuth";

function MainModelCardActions({ postData }: { postData: Post }) {
  const {
    _id: postId,
    user_id,
    user_name,
    likesCount,
    is_liked,
  } = 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 [showReportModal, setShowReportModal] = useState<boolean>(false);
  const [showCommentsModal, setShowCommentsModal] = useState<boolean>(false);
  const [showShareModal, setShowShareModal] = useState(false);
  const [showServicesModal, setShowServicesModal] = useState<boolean>(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);      
    } catch (error: unknown) {
      let errorMessage = "خطا در ارتباط با سرور";
    
      if (error instanceof Error) {
        // خطاهای معمول JS
        errorMessage = error.message;
      } else if (error instanceof AxiosError) {
        // خطاهای Axios
        errorMessage = error.response?.data?.message ?? error.message;
      }
    
      toast.error(errorMessage);
    
      setLiked(!newLiked);
      setLikesCount(likesCountState);
      console.error(error);
    }
    
  };
  
  

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

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

  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;
  

  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="flex items-center w-full justify-between mt-2">
        <RoundedButton
          onClick={() => setShowServicesModal(true)}
          className="text-sm px-4 h-8 max-sm:text-xs"
        >
          درخواست همکاری
        </RoundedButton>
        <div className="flex items-center gap-5 md:gap-10">
          <button
            onClick={() => setShowCommentsModal(!showCommentsModal)}
            className="flex flex-col items-center text-xs font-semibold gap-1"
          >
            <Image
              width={20}
              height={20}
              alt="message-text.svg"
              src="/images/icons/message-text.svg"
              className="dark:invert"
            />
            <span>
              {commentCount}
              <span className="mr-1 max-sm:text-xs">کامنت</span>
            </span>
          </button>
          <button
            onClick={() => shareUrl && setShowShareModal(true)}
            className="flex flex-col items-center text-xs font-semibold gap-1"
          >
            <Image
              width={20}
              height={20}
              alt="share.svg"
              src="/images/icons/share.svg"
              className="dark:invert"
            />
            <span className="max-sm:text-xs">اشتراک‌گذاری</span>
          </button>
          <button
            onClick={toggleLike}
            className="flex flex-col items-center text-xs font-semibold gap-1"
          >
            <Image
              width={20}
              height={20}
              alt="heart.svg"
              src={liked ? "/images/icons/red-heart.svg" : "/images/icons/heart.svg"}
              className="dark:invert"
            />
            <span>
              {likesCountState} <span className="max-sm:text-xs">لایک</span>
            </span>
          </button>
        </div>
      </div>
    </>
  );
}

export default MainModelCardActions;
