"use client";

import React, {
  useState,
  useRef,
  useEffect,
  useContext,
  createContext,
} from "react";
import { Post } 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 BoldIcon from "@/components/ui/BoldIcon";
import SwipeImageSlider from "./SwipeImageSlider";

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

function MainModelCard({
  postData,
  onMediaClick,
}: {
  postData: Post;
  onMediaClick?: () => void;
}) {
  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;

  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 [videoMuted, setVideoMuted] = useState(true);

  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),
    })) || [];

  // تابع برای ایجاد افکت 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;
    setVideoMuted(v.muted);
    setMuted(v.muted);

    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;
      setVideoMuted(muted);
    }
  }, [muted]);

  useEffect(() => {
    const v = videoRef.current;
    if (!v || type !== "video") return;
    const sync = () => setVideoMuted(v.muted);
    v.addEventListener("volumechange", sync);
    sync();
    return () => v.removeEventListener("volumechange", sync);
  }, [type, mediaFiles]);

  return (
    <div className="w-full flex flex-col px-1 max-w-[992px] mb-6 overflow-hidden">
      <Link
        href={`/users/${user_name}`}
        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={
                profile_image
                  ? buildStorageUrl(profile_image)
                  : "/images/fake-avatar.png"
              }
              alt={user_name}
              fill
              className="rounded-xl object-cover aspect-square"
              priority
              unoptimized
            />
          </div>
          <div className="font-semibold flex gap-2 flex-col-reverse ml-2 w-full">
            <div className="flex items-center gap-1 mt-1">
              <h2 className="max-sm:text-xs inline-flex items-center gap-1">
                {user_name}
                <VerificationBadge isVerified={is_verified} />
              </h2>
              <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="">
                <div className="text-[#15a9d6] flex gap-5 font-semibold">
                  {subExpertise && 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>
                  )}
                  {subExpertise && 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">
                <h4>{expertise}</h4>
                <span className="text-[#387E65] font-semibold">
                  {city?.name}
                </span>
                {matchedExpertise.map((item, index) => (
                  <h4 key={index} className="text-[#387E65] font-semibold">
                    {item}
                  </h4>
                ))}
              </div>
            </div>
          </div>
        </div>
      </Link>

      <div
        className={`overflow-hidden rounded-2xl ${onMediaClick ? "cursor-pointer" : ""}`}
        onClick={onMediaClick}
        onKeyDown={
          onMediaClick
            ? (e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  onMediaClick();
                }
              }
            : undefined
        }
        role={onMediaClick ? "button" : undefined}
        tabIndex={onMediaClick ? 0 : undefined}
        aria-label={onMediaClick ? "مشاهده تمام‌صفحه" : undefined}
      >
        {type === "image" && mediaFiles.length > 0 && (
          <SwipeImageSlider
            mediaFiles={mediaFiles}
            setImageLoading={setImageLoading}
          />
        )}

        {type === "video" && mediaFiles.length > 0 && (
          <div className="relative w-full rounded-2xl overflow-hidden bg-black">
            <video
              onClick={(e) => {
                if (onMediaClick) {
                  e.stopPropagation();
                  onMediaClick();
                  return;
                }
                handleVideoClick(e);
              }}
              ref={videoRef}
              src={mediaFiles[0].src}
              loop
              playsInline
              className="w-full h-auto object-contain"
              onLoadedData={() => setImageLoading(false)}
              muted={muted}
            />
            {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">
                <Image
                  height={40}
                  width={50}
                  src="/waiting.gif"
                  alt="waiting"
                />
              </div>
            )}
            <div className="pointer-events-none absolute left-3 top-3 z-50 rounded-full bg-black/50 p-2 backdrop-blur-md">
              {videoMuted ? (
                <BoldIcon name="volume-slash" size={20} tinted className="text-white" aria-label="بی‌صدا" />
              ) : (
                <BoldIcon name="volume-high" size={20} tinted className="text-white" aria-label="با صدا" />
              )}
            </div>
          </div>
        )}
      </div>

      <MainModelCardActions postData={postData} />
      {caption?.includes("@") && (
        <div className="mx-2 mt-1 flex items-center gap-1 text-xs text-neutral-500">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
            <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />
          </svg>
          <span>افراد تگ‌شده</span>
        </div>
      )}
      <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;
