"use client";

import { Course, Post } from "@/types/types";
import Image from "next/image";
import React, { useEffect, useState } from "react";
import ReportModal from "../main/ReportModal";
import CommentsModal from "./CommentsModal";
import useAxios from "@/hooks/useAxios";
import toast from "react-hot-toast";
import ModelDetailModal from "../models/ModelDetailModal";
import ModelServiceModal from "../models/ModelServiceModal";
import { useUserById } from "@/hooks/getUserById";
import { AxiosError } from "axios";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import { useRouter } from "next/navigation";
import { useRequireAuth } from "@/lib/auth/useRequireAuth";
import { SocialIconButton, SocialStatButton } from "@/components/ui/SocialStatButton";
import { profileActionBtnClass } from "@/lib/ui/buttonStyles";
import { cn } from "@/lib/utils";
import { useTranslation } from "react-i18next";

function MainModelCardActions({ postData }: { postData: Course }) {
  const { t } = useTranslation("common");
  const { _id, user_id, likes } = 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 [showServicesModal, setShowServicesModal] = useState<boolean>(false);
  const [liked, setLiked] = useState(false);
  const [likesCountState, setLikesCount] = useState(likes || 0);

  const { request, loading } = useAxios();
  const router = useRouter();
  const requireAuth = useRequireAuth();
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await request(
          "POST",
          `/academy/academy/course/is-like`,
          {
            courseId: _id,
          }
        );

        setLiked(response?.isLiked);
      } catch (error) {
        console.error("خطا در دریافت اطلاعات:", error);
      }
    };

    fetchData();
  }, []);

  const toggleLike = async () => {
    if (!requireAuth()) return;
    if (loading) return;

    if (liked === false) {
      try {
        const response = await request("POST", `/academy/academy/course/like`, {
          courseId: _id,
        });

        setLiked(true);
        setLikesCount(Number(likesCountState) + 1);
      } catch (error) {
        console.error("خطا در دریافت اطلاعات:", error);
      }
    }
    if (liked === true) {
      try {
        const response = await request(
          "POST",
          `/academy/academy/course/dislike`,
          {
            courseId: _id,
          }
        );

        setLiked(false);
        setLikesCount(Number(likesCountState) - 1);
      } catch (error) {
        console.error("خطا در دریافت اطلاعات:", error);
      }
    }
  };

  const [totalComments, setTotalComments] = useState(0);
  const [averageRate, setAverageRate] = useState(0);

  // دریافت تعداد کل کامنت‌ها و آمار

  useEffect(() => {
    const fetchCommentsStats = async () => {
      try {
        const response = await request(
          "GET",
          `/academy/course/${_id}/comments/count`
        );
        if (response?.success) {
          setTotalComments(response.data.totalComments);
          setAverageRate(response.data.averageRate);
        }
      } catch (error) {
        console.error("Error fetching stats:", error);
      }
    };

    fetchCommentsStats();
  }, []);

  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      toast.success(t("academy.linkCopied"));
    } catch (err) {
      console.error("Failed to copy:", err);
      toast.error(t("academy.copyFailed"));
    }
  };

  return (
    <>
      {showReportModal && (
        <ReportModal
          isOpen={showReportModal}
          onClose={() => setShowReportModal(false)}
        />
      )}
      {showCommentsModal && (
        <CommentsModal
          isOpen={showCommentsModal}
          onClose={() => setShowCommentsModal(false)}
          postData={postData}
        />
      )}
      {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="mt-2 flex w-full flex-row items-center justify-between px-6 sm:px-8">
        <button
          type="button"
          onClick={() => router.push(`/academy/${_id}/course`)}
          className={cn(profileActionBtnClass, "max-w-[120px] shrink-0")}
        >
          {t("academy.viewPackage")}
        </button>
        <SocialStatButton
          layout="horizontal"
          count={totalComments}
          onClick={() => setShowCommentsModal(!showCommentsModal)}
          aria-label={t("posts.comment")}
          icon={
            <Image
              width={20}
              height={20}
              alt=""
              src="/images/icons/message-text.svg"
              className="dark:invert"
            />
          }
        />
        <SocialIconButton
          layout="horizontal"
          onClick={(e) => {
              e.preventDefault();
              const url = `${window.location.origin}/academy/${_id}/course`;

              if (navigator.share) {
                navigator
                  .share({
                    title: t("academy.shareTitle"),
                    text: t("academy.shareText"),
                    url: url,
                  })
                  .catch((err) => {
                    console.log("Error sharing:", err);
                    copyToClipboard(url);
                  });
              } else {
                copyToClipboard(url);
              }
            }}
            aria-label={t("posts.share")}
            icon={
              <Image
                width={20}
                height={20}
                alt=""
                src="/images/icons/share.svg"
                className="dark:invert"
              />
            }
          />
        <SocialStatButton
          layout="horizontal"
          likeCount={likesCountState || 0}
          onClick={toggleLike}
          aria-label={t("posts.like")}
          icon={
            <Image
              width={20}
              height={20}
              alt=""
              src={
                liked
                  ? "/images/icons/red-heart.svg"
                  : "/images/icons/heart.svg"
              }
              className={liked ? "" : "dark:invert"}
            />
          }
        />
      </div>
    </>
  );
}

export default MainModelCardActions;
