"use client";

import React, {
  useState,
  useRef,
  useEffect,
  useContext,
} from "react";
import { Post } from "@/types/types";
import Image from "next/image";
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 BoldIcon from "@/components/ui/BoldIcon";
import ReelsPostActions, {
  ReelsCollaborationButton,
} from "./ReelsPostActions";
import { MutedContext } from "@/components/models/ModelPage/MainModelCardPost";
import Cookies from "js-cookie";
import { trackExploreInteraction } from "@/api/trackExploreInteraction";

interface ReelsPostCardProps {
  postData: Post;
  isActive?: boolean;
}

export default function ReelsPostCard({
  postData,
  isActive = false,
}: ReelsPostCardProps) {
  const {
    user_id,
    user_name,
    first_name,
    last_name,
    caption,
    files,
    type,
  } = postData;

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

  const [showFullCaption, setShowFullCaption] = useState(false);
  const [imageIndex, setImageIndex] = useState(0);
  const [imageLoading, setImageLoading] = useState(true);
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const containerRef = useRef<HTMLElement | null>(null);
  const viewStartedAtRef = useRef<number | null>(null);
  const watchCompleteTrackedRef = useRef(false);
  const [ripple, setRipple] = useState<{
    x: number;
    y: number;
    key: number;
  } | null>(null);

  const { muted, setMuted } = useContext(MutedContext);
  const [videoMuted, setVideoMuted] = useState(true);

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

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

  const handleVideoClick = (e: React.MouseEvent<HTMLVideoElement>) => {
    e.stopPropagation();
    const v = videoRef.current;
    if (!v) return;

    const rect = v.getBoundingClientRect();
    setRipple({
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
      key: Date.now(),
    });

    v.muted = !v.muted;
    setVideoMuted(v.muted);
    setMuted(v.muted);
    if (!v.muted) v.play().catch(() => {});
    setTimeout(() => setRipple(null), 600);
  };

  useEffect(() => {
    const video = videoRef.current;
    if (!video || type !== "video") return;

    if (isActive) {
      video.play().catch(() => {});
      video.muted = muted;
      setVideoMuted(muted);
    } else {
      video.pause();
    }
  }, [isActive, muted, type]);

  useEffect(() => {
    const token = Cookies.get("token") || "";
    const payload = {
      targetType: "post" as const,
      targetId: postData._id,
      authorId: postData.user_id,
      contentType: (postData.type === "video" ? "video" : "image") as
        | "video"
        | "image",
    };

    if (!isActive) {
      if (viewStartedAtRef.current && token) {
        const dwellMs = Date.now() - viewStartedAtRef.current;
        if (dwellMs < 2500) {
          trackExploreInteraction({ ...payload, action: "skip", dwellMs }, token);
        } else if (!watchCompleteTrackedRef.current && dwellMs >= 5000) {
          trackExploreInteraction({ ...payload, action: "dwell", dwellMs }, token);
        }
      }
      viewStartedAtRef.current = null;
      watchCompleteTrackedRef.current = false;
      return;
    }

    viewStartedAtRef.current = Date.now();
    watchCompleteTrackedRef.current = false;

    if (token) {
      trackExploreInteraction({ ...payload, action: "view" }, token);
    }

    const completeDelay =
      type === "video"
        ? Math.min(9000, Math.max(4000, (videoRef.current?.duration || 12) * 750))
        : 3500;

    const completeTimer = window.setTimeout(() => {
      if (!token || watchCompleteTrackedRef.current) return;
      watchCompleteTrackedRef.current = true;
      trackExploreInteraction(
        {
          ...payload,
          action: "watch_complete",
          dwellMs: completeDelay,
        },
        token
      );
    }, completeDelay);

    return () => {
      window.clearTimeout(completeTimer);
    };
  }, [isActive, postData._id, postData.user_id, postData.type, type]);

  const goToPrevImage = (e: React.MouseEvent) => {
    e.stopPropagation();
    setImageIndex((i) => (i > 0 ? i - 1 : mediaFiles.length - 1));
  };

  const goToNextImage = (e: React.MouseEvent) => {
    e.stopPropagation();
    setImageIndex((i) => (i < mediaFiles.length - 1 ? i + 1 : 0));
  };

  return (
    <article
      ref={containerRef}
      className="relative h-[100dvh] w-full snap-start snap-always overflow-hidden bg-black"
    >
      {/* Media */}
      <div className="absolute inset-0 flex items-center justify-center">
        {type === "image" && mediaFiles.length > 0 && (
          <>
            <Image
              src={mediaFiles[imageIndex].src}
              alt="post"
              fill
              className="object-contain"
              priority={isActive}
              onLoadingComplete={() => setImageLoading(false)}
              unoptimized
            />
            {mediaFiles.length > 1 && (
              <>
                <button
                  type="button"
                  onClick={goToPrevImage}
                  className="absolute right-2 top-1/2 z-10 -translate-y-1/2 rounded-full bg-black/30 p-2 text-white"
                  aria-label="قبلی"
                >
                  <BoldIcon name="arrow-right-3" size={20} tinted className="text-white" />
                </button>
                <button
                  type="button"
                  onClick={goToNextImage}
                  className="absolute left-2 top-1/2 z-10 -translate-y-1/2 rounded-full bg-black/30 p-2 text-white"
                  aria-label="بعدی"
                >
                  <BoldIcon name="arrow-left-2" size={20} tinted className="text-white" />
                </button>
                <div className="absolute top-[calc(3.5rem+env(safe-area-inset-top))] right-4 z-10 rounded-full bg-black/40 px-3 py-1 text-xs text-white">
                  {imageIndex + 1} / {mediaFiles.length}
                </div>
              </>
            )}
          </>
        )}

        {type === "video" && mediaFiles.length > 0 && (
          <>
            <video
              ref={videoRef}
              src={mediaFiles[0].src}
              loop
              playsInline
              className="h-full w-full object-contain"
              onClick={handleVideoClick}
              onLoadedData={() => setImageLoading(false)}
              muted={muted}
            />
            {ripple && (
              <span
                className="pointer-events-none absolute rounded-full bg-white/50 animate-ripple"
                style={{
                  left: ripple.x - 25,
                  top: ripple.y - 25,
                  width: 50,
                  height: 50,
                }}
                key={ripple.key}
              />
            )}
            <div className="pointer-events-none absolute right-3 top-[calc(3.5rem+env(safe-area-inset-top))] z-20 rounded-full bg-black/50 p-2 backdrop-blur-md">
              {videoMuted ? (
                <BoldIcon name="volume-slash" size={20} tinted className="text-white" />
              ) : (
                <BoldIcon name="volume-high" size={20} tinted className="text-white" />
              )}
            </div>
          </>
        )}

        {imageLoading && isActive && (
          <div className="absolute inset-0 z-10 flex items-center justify-center bg-black/40">
            <div className="h-10 w-10 animate-spin rounded-full border-4 border-white border-t-transparent" />
          </div>
        )}
      </div>

      {/* Actions — left side */}
      <ReelsPostActions postData={postData} />

      {/* Bottom user info — Instagram Reels style */}
      <div className="absolute inset-x-0 bottom-0 z-20 bg-gradient-to-t from-black/85 via-black/50 to-transparent px-4 pb-[calc(1.25rem+env(safe-area-inset-bottom))] pt-16">
        <div className="flex items-center gap-3">
          <Link
            href={`/users/${user_name}`}
            className="flex min-w-0 flex-1 items-center gap-2.5"
          >
            <div className="relative h-10 w-10 shrink-0 overflow-hidden rounded-full ring-2 ring-white/30">
              <Image
                src={
                  profile_image
                    ? buildStorageUrl(profile_image)
                    : "/images/fake-avatar.png"
                }
                alt={user_name}
                fill
                className="object-cover"
                unoptimized
              />
            </div>
            <div className="min-w-0 flex-1 text-white">
              <div className="flex items-center gap-1 truncate text-sm font-semibold">
                <span className="truncate">{user_name}</span>
                <VerificationBadge isVerified={is_verified} />
              </div>
              <p className="truncate text-xs text-white/80">
                {first_name} {last_name}
              </p>
            </div>
          </Link>
          <ReelsCollaborationButton postData={postData} />
        </div>

        {caption && (
          <p className="mt-2 line-clamp-2 text-sm leading-relaxed text-white/95">
            {displayCaption}
            {caption.length > 80 && (
              <button
                type="button"
                className="mr-1 font-semibold text-white/70"
                onClick={() => setShowFullCaption(!showFullCaption)}
              >
                {showFullCaption ? "کمتر" : "بیشتر"}
              </button>
            )}
          </p>
        )}
      </div>

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