"use client";

import React, { useState, useRef, useEffect, useContext, createContext } from "react";
import { Post } from "@/types/types";
import Image from "next/image";
import MainModelCardActions from "../MainModelCard/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 Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";

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

function MainModelCard({ postData }: { postData: Post }) {
  const {
    user_id,
    user_name,
    first_name,
    last_name,
    expertise,
    city,
    user_level,
    caption,
    files,
    type,
  } = postData;

  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;
// console.log(user);

  const [showFullCaption, setShowFullCaption] = useState(false);
  const [currentSlide, setCurrentSlide] = useState(0);
  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))
  );

  const mediaFiles =
    files?.map((file) => ({
      ...file,
      src: buildStorageUrl(file.path),
    })) || [];

  const sliderSettings = {
    dots: mediaFiles.length > 1,
    infinite: mediaFiles.length > 1,
    speed: 500,
    slidesToShow: 1,
    slidesToScroll: 1,
    arrows: true,
    autoplay: false,
    adaptiveHeight: false,
    lazyLoad: "progressive" as const,
    afterChange: (index: number) => setCurrentSlide(index),
  };

  // تابع برای ایجاد افکت 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;

    // تنظیم افکت ripple
    setRipple({ x, y, key: Date.now() });

    // تغییر وضعیت صدا (گلوبال)
    const newMuted = !muted;
    setMuted(newMuted);
    v.muted = newMuted;
    if (!newMuted) {
      v.play().catch(() => {
        /* ignore */
      });
    }

    // حذف افکت بعد از اتمام انیمیشن
    setTimeout(() => {
      setRipple(null);
    }, 600); // مدت زمان انیمیشن (600ms)
  };

  // استفاده از 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(() => {
    const video = videoRef.current;
    if (video) {
      video.muted = muted;
    }
  }, [muted]);

  return (
    <div className="w-full z-[999]  min-h-[85vh] max-h-[90vh] flex flex-col px-4 mx-auto max-w-[992px] mb-6 overflow-hidden">
      <Link
        href={`/users/${user_name}`}
        className="flex w-full 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={
                profile_image
                  ? buildStorageUrl(profile_image)
                  : "/images/fake-avatar.png"
              }
              alt={user_name}
              fill
              className="rounded-xl object-cover aspect-square"
              priority
            />
          </div>
          <div className="font-semibold flex gap-2 flex-col-reverse ml-2 w-full">
            <div className="flex items-center gap-1 mt-1">
              <span className="max-sm:text-xs inline-flex items-center gap-1">
                {user_name}
                <VerificationBadge isVerified={is_verified} />
              </span>
              <div className="flex items-center gap-0.5 justify-center">
                <span className="mr-2">{user_score || 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">{rate || 0}</span>
                <Image
                  width={22}
                  height={22}
                  alt="star icon"
                  src="/images/icons/star1.svg"
                />
              </div>
            </div>
            <div className="flex justify-between items-center">
              <div className="max-sm:text-xs">
                {first_name} {last_name}
              </div>
              <div className="hidden">
                <div className="text-[#15a9d6] pt-1 flex gap-5 mt-3 font-semibold">
                  {matchedExpertise2.length > 0 && (
                    <span>
                      <svg
                        width="24"
                        height="24"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        xmlns="http://www.w3.org/2000/svg"
                      >
                        <path
                          d="M5.99953 5.17031L4.02953 6.46031C2.09953 7.72031 2.09953 10.5403 4.02953 11.8003L10.0495 15.7303C11.1295 16.4403 12.9095 16.4403 13.9895 15.7303L19.9795 11.8003C21.8995 10.5403 21.8995 7.73031 19.9795 6.47031L13.9895 2.54031C12.9095 1.83031 11.1295 1.83031 10.0495 2.54031"
                          strokeWidth="1.5"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        />
                        <path
                          d="M5.63012 13.0801L5.62012 17.7701C5.62012 19.0401 6.60012 20.4001 7.80012 20.8001L10.9901 21.8601C11.5401 22.0401 12.4501 22.0401 13.0101 21.8601L16.2001 20.8001C17.4001 20.4001 18.3801 19.0401 18.3801 17.7701V13.1301"
                          strokeWidth="1.5"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        />
                        <path
                          d="M21.4004 15V9"
                          strokeWidth="1.5"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        />
                      </svg>
                    </span>
                  )}
                  {matchedExpertise3.length > 0 && (
                    <span>
                      <svg
                        width="24"
                        height="24"
                        viewBox="0 0 24 24"
                        fill="none"
                        xmlns="http://www.w3.org/2000/svg"
                      >
                        <path
                          d="M2 22H22"
                          stroke="currentColor"
                          strokeWidth="1.5"
                          strokeMiterlimit="10"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        />
                        <path
                          d="M12 2C13.6 2.64 15.4 2.64 17 2V5C15.4 5.64 13.6 5.64 12 5V2Z"
                          stroke="currentColor"
                          strokeWidth="1.5"
                          strokeMiterlimit="10"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        />
                        <path
                          d="M12 5V8"
                          stroke="currentColor"
                          strokeWidth="1.5"
                          strokeMiterlimit="10"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        />
                        <path
                          d="M4 15.91V22H20V11C20 9 19 8 17 8H7C5 8 4 9 4 11V12"
                          stroke="currentColor"
                          strokeWidth="1.5"
                          strokeMiterlimit="10"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        />
                        <path
                          d="M4 12H19.42"
                          stroke="currentColor"
                          strokeWidth="1.5"
                          strokeMiterlimit="10"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        />
                        <path
                          d="M7.98999 12V22"
                          stroke="currentColor"
                          strokeWidth="1.5"
                          strokeMiterlimit="10"
                          strokeLinejoin="round"
                        />
                        <path
                          d="M11.99 12V22"
                          stroke="currentColor"
                          strokeWidth="1.5"
                          strokeMiterlimit="10"
                          strokeLinejoin="round"
                        />
                        <path
                          d="M15.99 12V22"
                          stroke="currentColor"
                          strokeWidth="1.5"
                          strokeMiterlimit="10"
                          strokeLinejoin="round"
                        />
                      </svg>
                    </span>
                  )}
                </div>
              </div>
            </div>
            <div className="max-sm:text-xs items-center text-[#387E65] flex w-full justify-between">
              {user_level || "تازه وارد"}
              <div className="text-[#387E65] pt-1 flex gap-5 font-semibold">
                <span>{expertise}</span>
                <span className="text-[#387E65] font-semibold">
                  {city?.name}
                </span>
                {matchedExpertise.map((item, index) => (
                  <span key={index} className="text-[#387E65] font-semibold">
                    {item}
                  </span>
                ))}
              </div>
            </div>
          </div>
        </div>
      </Link>

      <div className="relative flex-grow overflow-hidden rounded-2xl">
        {type === "image" && mediaFiles.length > 0 && (
          <div className="relative w-full h-full">
            <Slider {...sliderSettings}>
              {mediaFiles.map((file, idx) => (
                <div
                  key={idx}
                  className="relative w-full h-[calc(100vh-290px)] overflow-hidden"
                >
                  <Image
                    src={file.src}
                    alt={`post-image-${idx}`}
                    fill
                    className="object-contain h-full"
                    onLoadingComplete={() => setImageLoading(false)}
                    loading={idx === 0 ? "eager" : "lazy"}
                  />
                  {imageLoading && idx === currentSlide && (
                    <div className="absolute inset-0 flex justify-center items-center bg-black/30 z-10">
                      <div className="w-12 h-12 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
                    </div>
                  )}
                </div>
              ))}
            </Slider>
            {mediaFiles.length > 1 && (
              <div className="absolute bottom-2 right-2 bg-black/40 text-white px-3 py-1 rounded-full text-sm">
                {currentSlide + 1} / {mediaFiles.length}
              </div>
            )}
          </div>
        )}
        {type === "video" && mediaFiles.length > 0 && (
          <div className="relative w-full h-[calc(100vh-150px)]  overflow-hidden">
            <video
              onClick={handleVideoClick}
              ref={videoRef}
              src={mediaFiles[0].src}
              loop
              playsInline
              className="w-full h-full object-contain"
              onLoadedData={() => setImageLoading(false)}
              muted={muted} // این مقدار همیشه از گلوبال گرفته می‌شود
              // autoPlay حذف شده، چون حالا با observer مدیریت می‌شود
            />
            {ripple && (
              <span
                className="absolute rounded-full bg-white/50 animate-ripple"
                style={{
                  left: ripple.x - 25, // نصف عرض دایره
                  top: ripple.y - 25,  // نصف ارتفاع دایره
                  width: 50,
                  height: 50,
                }}
                key={ripple.key}
              />
            )}
            {imageLoading && (
              <div className="absolute inset-0 flex justify-center items-center bg-black/30 z-10">
                <div className="w-12 h-12 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
              </div>
            )}
           
          </div>
        )}
      </div>

      <MainModelCardActions postData={postData} />
      <p className="text-sm font-medium mt-2 mx-2 leading-6">
        {displayCaption}
        {caption?.length && caption.length > 40 && (
          <span
            className="text-blue-500 hover:underline cursor-pointer ml-1 transition-colors duration-200"
            onClick={() => setShowFullCaption(!showFullCaption)}
          >
            {showFullCaption ? "کمتر" : "بیشتر"}
          </span>
        )}
      </p>

      <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;
