"use client";

import React, {
  useState,
  useRef,
  useEffect,
  useContext,
  createContext,
  useCallback,
} from "react";
import { Academy, Course } from "@/types/types";
import Image from "next/image";
import MainModelCardActions from "./MainModelCardActions";
import Link from "next/link";
import { IMAGE_BASE_URL, buildStorageUrl } from "@/components/main/BaseUrl";
import VerificationBadge from "@/components/main/VerificationBadge";
import { useUserById } from "@/hooks/getUserById";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import useAxios from "@/hooks/useAxios";
import { useRouter } from "next/navigation";
import { forEach } from "lodash";

// ایجاد Context برای به اشتراک گذاشتن وضعیت muted بین همه کارت‌ها
const MutedContext = createContext<{
  muted: boolean;
  setMuted: React.Dispatch<React.SetStateAction<boolean>>;
}>({
  muted: true,
  setMuted: () => {},
});

interface AcademyResponse {
  academy: Academy;
}

function MainModelCard({ postData }: { postData: Course }) {
  const {
    user_id,
    caption,
    type,
    price,
    cuorse_name,
    category,
    offer,
    academyId,
    number_of_course_content,
    course_image,
  } = postData;

  // console.log(postData._id);
  

  const user = useUserById(user_id);
  const profile_image = user?.profile_image;
  const is_verified = user?.is_verified;
  const user_score = user?.user_score;
  const rate = user?.rate;

  const { request } = useAxios();
  const router = useRouter()
  const [academy, setAcademy] = useState<Academy | null>(null);


  const { _id } = postData;

  const [newScore, setNewScore] = useState<number>(0);
  const [rating, setRating] = useState<number>(0);
  const [comments, setComments] = useState<Comments[]>([]);
  const [totalComments, setTotalComments] = useState(0);
  const [averageRate, setAverageRate] = useState(0);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [statusFilter, setStatusFilter] = useState<string>("accepted");
  const [sortBy, setSortBy] = useState<string>("createdAt");
  const [sortOrder, setSortOrder] = useState<string>("desc");
  const [usersCache, setUsersCache] = useState<Record<string, any>>({});

 
  const containerRef = useRef<HTMLDivElement>(null);

  // تابع دریافت اطلاعات کاربر با caching
  const fetchUserInfo = async (userId: string) => {
    if (usersCache[userId]) {
      return usersCache[userId];
    }

    try {
      const response = await request("GET", `/profile/${userId}`);
      if (response?.user) {
        const userData = response.user;
        setUsersCache((prev) => ({ ...prev, [userId]: userData }));
        return userData;
      }
    } catch (error) {
      console.error(`Error fetching user ${userId}:`, error);
    }
    return null;
  };

  // دریافت تعداد کل کامنت‌ها و آمار
  const fetchCommentsStats = async () => {
    if (!_id) return;
    
    try {
      const response = await request(
        "GET",
        `/academy/course/${_id}/comments/count`
      );
      if (response?.success) {
        setTotalComments(response.data.totalComments);
        setAverageRate(response.data.averageRate || 0);
      }
    } catch (error) {
      console.error("Error fetching stats:", error);
    }
  };

  // دریافت لیست کامنت‌ها
  const fetchComments = async (pageNum: number, append = false) => {
    if (loading || !_id) return;

    setLoading(true);
    try {
      const response = await request(
        "GET",
        `/academy/course/${_id}/comments?page=${pageNum}&limit=20&status=${statusFilter}&sortBy=${sortBy}&sortOrder=${sortOrder}`
      );

      let sum = 0;
      let count = 0;
      
      response.data.stats.rateDistribution.forEach(element => {
        sum += Number(element);
        count++;
      });
      
      const average = sum / count;
      const averagesum = sum *1;

      const roundedRating = Math.round(average * 10) / 10
      setRating(roundedRating);
      setNewScore(averagesum);


      
      

      if (response?.success) {
        let newComments = response.data.comments;
        const pagination = response.data.pagination;

        if (newComments && newComments.length > 0) {
          // بررسی اینکه آیا بک‌اند اطلاعات کاربر را populate کرده است
          if (newComments[0]?.user_id?.user_name) {
            // اطلاعات کاربر قبلاً داخل کامنت است
            setComments((prev) =>
              append ? [...prev, ...newComments] : newComments
            );
          } else {
            // اگر بک‌اند فقط user_id را برگردانده، اطلاعات کاربر را بگیریم
            const uniqueUserIds = [...new Set(newComments.map((c) => c.user_id))];
            
            // دریافت اطلاعات همه کاربران به صورت همزمان
            const usersData = await Promise.all(
              uniqueUserIds.map((id) => fetchUserInfo(id))
            );
            
            // ساخت mapping از userId به اطلاعات کاربر
            const userMap: Record<string, any> = {};
            uniqueUserIds.forEach((id, index) => {
              userMap[id] = usersData[index];
            });
            
            // ترکیب کامنت‌ها با اطلاعات کاربران
            const commentsWithUsers = newComments.map((comment) => ({
              ...comment,
              user_id: userMap[comment.user_id] || {
                _id: comment.user_id,
                user_name: "کاربر ناشناس",
                profile_image: null,
                is_verified: "unverified"
              },
            }));
            
            setComments((prev) =>
              append ? [...prev, ...commentsWithUsers] : commentsWithUsers
            );
          }
        } else {
          setComments(append ? [...prev] : []);
        }

        setHasMore(pagination?.hasNextPage || false);
        if (pagination?.totalItems) {
          setTotalComments(pagination.totalItems);
        }
      }
    } catch (error) {
      console.error("Error fetching comments:", error);
      toast.error("خطا در دریافت نظرات");
    } finally {
      setLoading(false);
    }
  };

  // لود اولیه و هنگام تغییر فیلترها
  useEffect(() => {
    if (_id) {
      setPage(1);
      setComments([]);
      fetchComments(1, false);
      fetchCommentsStats();
    }
  }, [ _id, statusFilter, sortBy, sortOrder]);

  // اینفینیت اسکرول
  const observer = useRef<IntersectionObserver | null>(null);
  const lastCommentRef = useCallback(
    (node: HTMLDivElement) => {
      if (loading) return;
      if (observer.current) observer.current.disconnect();
      observer.current = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting && hasMore) {
          setPage((prev) => prev + 1);
        }
      });
      if (node) observer.current.observe(node);
    },
    [loading, hasMore]
  );

  useEffect(() => {
    if (page > 1) {
      fetchComments(page, true);
    }
  }, [page]);
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = (await request("POST", `/academy/findAcademyById`, {
          _id: academyId,
        })) as AcademyResponse;
        setAcademy(response?.academy);
        console.log(response);
      } catch (error) {
        console.error("خطا در دریافت اطلاعات:", error);
      }
    };

    fetchData();
  }, []);

  const [showFullCaption, setShowFullCaption] = useState(false);

  const [imageLoading, setImageLoading] = useState(true);
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const [ripple, setRipple] = useState<{
    x: number;
    y: number;
    key: number;
  } | null>(null);

  // استفاده از Context برای وضعیت muted گلوبال
  const { muted, setMuted } = useContext(MutedContext);

  const displayCaption = showFullCaption ? caption : caption?.slice(0, 40);

  const subExpertise = user?.sub_expertise || [];
  const keywords = ["نمونه کار دارم", "آرایشگر سیار", "عکاس سیار"];
  const keywords2 = ["آموزشگاه دارم"];
  const keywords3 = ["سالن دارم", "آتیله دارم"];

  const matchedExpertise = subExpertise.filter((item) =>
    keywords.some((keyword) => item.includes(keyword))
  );
  const matchedExpertise2 = subExpertise.filter((item) =>
    keywords2.some((keyword) => item.includes(keyword))
  );
  const matchedExpertise3 = subExpertise.filter((item) =>
    keywords3.some((keyword) => item.includes(keyword))
  );

  // تابع برای ایجاد افکت ripple و تغییر وضعیت صدا
  const handleVideoClick = (e: React.MouseEvent<HTMLVideoElement>) => {
    const v = videoRef.current;
    if (!v) return;

    const rect = v.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    setRipple({ x, y, key: Date.now() });

    // --- مهمترین اصلاح ---
    v.muted = !v.muted; // اول وضعیت ویدیو را تغییر بده
    setMuted(v.muted); // بعد context را Sync کن

    if (!v.muted) {
      v.play().catch(() => {});
    }

    setTimeout(() => setRipple(null), 600);
  };

  // استفاده از IntersectionObserver برای پخش/توقف ویدیو بر اساس ویوپورت
  useEffect(() => {
    const video = videoRef.current;
    if (!video || type !== "video") return;

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            // ویدیو در ویوپورت است: پخش کن
            video.play().catch(() => {
              /* ignore: ممکن است به دلیل محدودیت‌های مرورگر */
            });
            video.muted = muted; // اعمال وضعیت گلوبال
          } else {
            // ویدیو خارج از ویوپورت: توقف کن
            video.pause();
          }
        });
      },
      {
        threshold: 0.5, // حداقل 50% ویدیو باید در ویوپورت باشد
      }
    );

    observer.observe(video);

    return () => {
      observer.unobserve(video);
    };
  }, [muted, type]);

  // اعمال وضعیت muted گلوبال هنگام mount یا تغییر muted
  useEffect(() => {
    if (videoRef.current) {
      videoRef.current.muted = muted;
    }
  }, [muted]);

  return (
    <div
      className={`
      relative w-full flex flex-col px-1 max-w-[992px] mb-6 overflow-hidden rounded-2xl
      transition-all duration-300
      ${type === "pro" ? "shadow-[0_0px_30px_rgb(255,16,125,0.60)] p-3" : ""}
    `}
    >
{/* {type === "pro" && (
        <div className="absolute top-30 left-3 z-10 bg-gradient-to-r from-[#FF107D] to-[#FF6B9D] text-white text-xs font-bold px-3 py-1.5 rounded-full shadow-lg flex items-center gap-1.5 backdrop-blur-sm">
          <svg
            width="14"
            height="14"
            viewBox="0 0 24 24"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M12 2L15 8.5L22 9.5L17 14L18.5 21L12 17.5L5.5 21L7 14L2 9.5L9 8.5L12 2Z"
              fill="currentColor"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinejoin="round"
            />
          </svg>
          <span>نسخه پرو</span>
        </div>
      )} */}
      <Link
        href={`/academy/profile/${academyId}`}
        className="flex text-sm justify-between py-2"
      >
        <div className="flex items-center w-full">
          <div className="relative max-w-[72px] min-w-[72px] max-h-[72px] min-h-[72px] ml-2">
            <Image
              src={
                academy?.academy_image
                  ? IMAGE_BASE_URL + academy?.academy_image
                  : "/images/fake-avatar.png"
              }
              alt={cuorse_name}
              fill
              className="rounded-xl object-cover"
              priority
            />
          </div>
          <div className="font-semibold flex gap-2 flex-col ml-2 w-full">
            <div className="max-sm:text-xs items-center text-[#387E65] flex w-full justify-between">
              تعداد ویدیو : {number_of_course_content}
              <div className="text-[#387E65] pt-1 flex gap-5 font-semibold">
                <h4>{category}</h4>
                {matchedExpertise.map((item, index) => (
                  <h4 key={index} className="text-[#387E65] font-semibold">
                    {item}
                  </h4>
                ))}
              </div>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-[#0090ff] text-xl font-semibold">
                {offer && parseInt(offer) > 0 ? (
                  <>
                    {/* <span className="line-through text-muted-foreground text-xs"> 
                      {parseInt(price).toLocaleString()}
                    </span>{" "}
                    <span className=" text-muted-foreground text-xs">
                      تومان
                    </span> */}
                    {(
                      (parseInt(price) * (100 - parseInt(offer))) /
                      100
                    ).toLocaleString()}
                  </>
                ) : (
                  parseInt(price).toLocaleString()
                )}
                <span className="text-[#0090ff] text-xl font-semibold">تومان</span>
                <span className="text-[#ff0000] text-xl font-semibold">
                  {offer && Number(offer) > 0 ? `%${offer}` : ""}
                </span>
              </span>
            </div>
            <div className="flex items-center gap-1 mt-1">
              <h2 className="max-sm:text-xs inline-flex items-center gap-1">
                {cuorse_name}
                <VerificationBadge isVerified={is_verified} />
              </h2>
              <div className="flex items-center gap-0.5 justify-center">
                <span className="mr-2">{newScore || 0}</span>
                <Image
                  width={22}
                  height={22}
                  alt="star icon"
                  src="/images/icons/medal-star.svg"
                />
              </div>
              <div className="flex items-center gap-0.5 justify-center">
                <span className="mr-2">{rating || 0}</span>
                <Image
                  width={22}
                  height={22}
                  alt="star icon"
                  src="/images/icons/star1.svg"
                />
              </div>
            </div>
          </div>
        </div>
      </Link>

      <div  onClick={() => router.push(`/academy/${postData._id}/course`)} className=" overflow-hidden rounded-2xl">
        <div
          className="w-full flex-shrink-0 flex justify-center items-center p-2"
          style={{ width: "100%" }}
        >
          <Image
            src={IMAGE_BASE_URL + course_image}
            alt={`media-${course_image}`}
            width={1000}
            height={1000}
            loading={"lazy"}
            className="object-contain w-full min-h-[30vh] rounded-xl shadow-lg transition-opacity duration-300"
            onLoadingComplete={() => setImageLoading?.(false)}
          />
        </div>
      </div>

      <MainModelCardActions postData={postData} />
      <h3 className="text-sm font-medium mt-2 mx-2 leading-6 flex flex-wrap gap-1 text-justify">
        {(showFullCaption
          ? caption
          : caption?.slice(0, 40) +
            (caption && caption.length > 40 ? "  " : " ")
        )
          ?.split(/(\s+)/)
          .map((part, index) =>
            part.startsWith("#") ? (
              <Link
                key={index}
                href={`/?hashtag=${part.replace("#", "")}`}
                className="text-blue-500 font-bold"
              >
                {part}
              </Link>
            ) : (
              part
            )
          )}
        {caption && caption.length > 40 && (
          <span
            className="text-white-500 cursor-pointer font-bold"
            onClick={() => setShowFullCaption(!showFullCaption)}
          >
            {showFullCaption ? "کمتر" : "بیشتر"}
          </span>
        )}
      </h3>

      <style jsx>{`
        .animate-ripple {
          animation: ripple 600ms ease-out;
          pointer-events: none;
        }
        @keyframes ripple {
          0% {
            transform: scale(0);
            opacity: 0.5;
          }
          100% {
            transform: scale(4);
            opacity: 0;
          }
        }
      `}</style>
    </div>
  );
}

// Provider برای به اشتراک گذاشتن وضعیت muted
export const MutedProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const [muted, setMuted] = useState(true);

  return (
    <MutedContext.Provider value={{ muted, setMuted }}>
      {children}
    </MutedContext.Provider>
  );
};

export default MainModelCard;
