"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 RoundedButton from "@/components/elements/RoundedButton";
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";

function MainModelCardActions({ postData }: { postData: Course }) {
  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 اضافه کنید
      alert('لینک کپی شد!');
    } catch (err) {
      console.error('Failed to copy:', err);
      alert('کپی نشد، لطفاً دستی کپی کنید');
    }
  };

  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="flex items-center w-full justify-between mt-2">
        <RoundedButton
          onClick={() => router.push(`/academy/${_id}/course`)}
          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>
              {totalComments}
              <span className="mr-1 max-sm:text-xs">کامنت</span>
            </span>
          </button>
          <button
            onClick={(e) => {
              e.preventDefault();
              const url = `${window.location.origin}/academy/${_id}/course`;

              // روش اول: استفاده از Web Share API (بهترین برای موبایل)
              if (navigator.share) {
                navigator
                  .share({
                    title: "دوره آموزشی",
                    text: "این دوره رو ببینید!",
                    url: url,
                  })
                  .catch((err) => {
                    console.log("Error sharing:", err);
                    // fallback
                    copyToClipboard(url);
                  });
              } else {
                // روش دوم: کپی در کلیپ‌بورد (برای دسکتاپ)
                copyToClipboard(url);
              }
            }}
            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 || 0}{" "}
              <span className="max-sm:text-xs">لایک</span>
            </span>
          </button>
        </div>
      </div>
    </>
  );
}

export default MainModelCardActions;
