"use client";

import React, { useRef, useEffect, useContext, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { motion, AnimatePresence } from "framer-motion";
import { AcademyExploreItem } from "@/api/fetchAcademyExplore";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import BoldIcon from "@/components/ui/BoldIcon";
import SharePostModal from "@/components/main/SharePostModal";
import { MutedContext } from "@/components/models/ModelPage/MainModelCardPost";
import { ReelsCollaborationButton } from "@/components/posts/ReelsPostActions";

function getAcademyMedia(item: AcademyExploreItem): {
  kind: "video" | "image";
  src: string;
} | null {
  const file = item.files?.[0];
  if (file?.path) {
    const src = buildStorageUrl(file.path);
    const isVideo = item.type === "video" || file.type === "video";
    return { kind: isVideo ? "video" : "image", src };
  }
  if (item.course_video) {
    return { kind: "video", src: buildStorageUrl(item.course_video) };
  }
  const imagePath = item.course_images?.[0] || item.course_image;
  if (imagePath) {
    return { kind: "image", src: buildStorageUrl(imagePath) };
  }
  return null;
}

function ReelsAcademyActions({
  item,
  shareUrl,
}: {
  item: AcademyExploreItem;
  shareUrl: string;
}) {
  const [expanded, setExpanded] = useState(false);
  const [showShareModal, setShowShareModal] = useState(false);
  const actionButtonClass =
    "flex flex-col items-center gap-1 text-white drop-shadow-md";

  return (
    <>
      <SharePostModal
        open={showShareModal}
        onClose={() => setShowShareModal(false)}
        url={shareUrl}
      />
      <div className="absolute left-3 bottom-36 z-30 flex flex-col items-center">
        <AnimatePresence mode="wait">
          {!expanded ? (
            <motion.button
              key="trigger"
              type="button"
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.8 }}
              transition={{ duration: 0.2 }}
              onClick={() => setExpanded(true)}
              className="flex h-11 w-11 items-center justify-center rounded-full bg-black/40 backdrop-blur-md"
              aria-label="نمایش عملیات"
            >
              <BoldIcon name="grid-3" size={24} className="block dark:invert" />
            </motion.button>
          ) : (
            <motion.div
              key="actions"
              initial={{ opacity: 0, y: 12 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: 12 }}
              transition={{ duration: 0.25, ease: "easeOut" }}
              className="flex flex-col items-center gap-5"
            >
              <div className={actionButtonClass}>
                <Image
                  width={28}
                  height={28}
                  alt="heart"
                  src="/images/icons/heart.svg"
                  className="invert drop-shadow-lg"
                />
                <span className="text-xs font-semibold">
                  {item.likesCount ?? 0}
                </span>
              </div>
              <button
                type="button"
                onClick={() => shareUrl && setShowShareModal(true)}
                className={actionButtonClass}
                aria-label="اشتراک‌گذاری"
              >
                <Image
                  width={28}
                  height={28}
                  alt="share"
                  src="/images/icons/share.svg"
                  className="invert drop-shadow-lg"
                />
              </button>
              <button
                type="button"
                onClick={() => setExpanded(false)}
                className="mt-1 flex h-9 w-9 items-center justify-center rounded-full bg-black/40 backdrop-blur-md"
                aria-label="بستن"
              >
                <BoldIcon name="close-circle" size={20} tinted className="text-white" />
              </button>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </>
  );
}

export default function ReelsAcademyCard({
  item,
  isActive = false,
}: {
  item: AcademyExploreItem;
  isActive?: boolean;
}) {
  const media = getAcademyMedia(item);
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const { muted, setMuted } = useContext(MutedContext);
  const [videoMuted, setVideoMuted] = useState(true);

  const displayName =
    [item.first_name, item.last_name].filter(Boolean).join(" ") ||
    item.teacher_name ||
    item.user_name ||
    "آموزشگاه";

  const shareUrl = item.courseId
    ? `https://modstagram.com/academy/${item.courseId}/course`
    : "";

  const collaborationPost = {
    _id: item._id,
    user_id: item.user_id || "",
    user_name: item.user_name || "",
    first_name: item.first_name || "",
    last_name: item.last_name || "",
    likesCount: item.likesCount ?? 0,
    is_liked: false,
    commentsCount: 0,
    files: [],
  };

  useEffect(() => {
    const video = videoRef.current;
    if (!video || media?.kind !== "video") return;
    if (isActive) {
      video.play().catch(() => {});
      video.muted = muted;
      setVideoMuted(muted);
    } else {
      video.pause();
    }
  }, [isActive, muted, media?.kind]);

  if (!media) return null;

  return (
    <article className="relative h-[100dvh] w-full snap-start snap-always overflow-hidden bg-black">
      <div className="absolute inset-0 flex items-center justify-center">
        {media.kind === "video" ? (
          <>
            <video
              ref={videoRef}
              src={media.src}
              loop
              playsInline
              className="h-full w-full object-contain"
              muted={muted}
              onClick={(e) => {
                e.stopPropagation();
                const v = videoRef.current;
                if (!v) return;
                v.muted = !v.muted;
                setVideoMuted(v.muted);
                setMuted(v.muted);
              }}
            />
            <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>
          </>
        ) : (
          <Image src={media.src} alt="" fill className="object-contain" priority={isActive} />
        )}
        <span className="absolute right-3 top-[calc(3.5rem+env(safe-area-inset-top))] z-10 rounded-md bg-emerald-600/90 px-2 py-1 text-[10px] font-medium text-white">
          آموزش رایگان
        </span>
      </div>

      <ReelsAcademyActions item={item} shareUrl={shareUrl} />

      <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={item.user_name ? `/users/${item.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 bg-neutral-700 ring-2 ring-white/30">
              {item.profile_image ? (
                <Image
                  src={buildStorageUrl(item.profile_image)}
                  alt=""
                  fill
                  className="object-cover"
                  unoptimized
                />
              ) : null}
            </div>
            <div className="min-w-0 flex-1 text-white">
              <div className="truncate text-sm font-semibold">
                {item.user_name || displayName}
              </div>
              <p className="truncate text-xs text-white/80">{displayName}</p>
            </div>
          </Link>
          {item.user_id ? (
            <ReelsCollaborationButton postData={collaborationPost as never} />
          ) : null}
        </div>
        {(item.caption || item.course_name) && (
          <p className="mt-2 line-clamp-2 text-sm leading-relaxed text-white/95">
            {item.caption || item.course_name}
          </p>
        )}
      </div>
    </article>
  );
}
