"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { playMedia } from "@/store/slices/playerSlice";
import { useAddView } from "@/hooks/useAddView";
import { useAddToHistory } from "@/hooks/useAddToHistory";
import { useSubscribe } from "@/hooks/useSubscribe";
import { useLikeDislike } from "@/hooks/useLikeDislike";
import { useShare } from "@/hooks/useShare";
import { VideoPlayer, VideoPlayerSkeleton } from "@/components/video/VideoPlayer";
import { CommentSection } from "@/components/shared/CommentSection";
import { ArrowLeft, Eye, ThumbsUp, ThumbsDown, MessageCircle, Users, Check, Share2 } from "lucide-react";
import Image from "next/image";
import type { RentItem } from "@/services/rentService";

/* ── helpers ─────────────────────────────────────────────────────────────── */

function getContentTypeForPlayer(contentType: number): "video" | "short" {
  return contentType === 3 ? "short" : "video";
}

/* ── info section ────────────────────────────────────────────────────────── */

function RentVideoInfo({ item }: { item: RentItem }) {
  const [descExpanded, setDescExpanded] = useState(false);
  const [commentOpen, setCommentOpen] = useState(false);
  const [likeAnim, setLikeAnim] = useState(false);
  const { share, copied } = useShare();

  const { subscribed, loading: subLoading, toggle } = useSubscribe(
    item.channelUserId,
    item.isSubscribed,
  );

  const { liked, disliked, totalLikes, totalDislikes, handleLike, handleDislike } =
    useLikeDislike({
      contentId: item.id,
      contentType: item.contentType,
      initialReaction: item.isUserLikeDislike,
      initialLikes: item.totalLike,
      initialDislikes: item.totalDislike,
    });

  const onLike = () => {
    if (!liked) { setLikeAnim(true); setTimeout(() => setLikeAnim(false), 400); }
    handleLike();
  };

  return (
    <div className="flex flex-col gap-0 mt-3">
      {/* Title */}
      <h1 className="text-base font-bold leading-snug" style={{ letterSpacing: "-0.01em", color: "var(--text-primary)" }}>
        {item.title}
      </h1>

      {/* Meta */}
      <div className="flex items-center gap-2 mt-1.5 flex-wrap">
        <span className="text-xs" style={{ color: "#888" }}>{item.views} views</span>
        <span style={{ color: "#555" }}>·</span>
        <span className="text-xs" style={{ color: "#888" }}>{item.uploadedAt}</span>
        {item.category && (
          <>
            <span style={{ color: "#555" }}>·</span>
            <span className="text-[10px] font-semibold px-2 py-0.5 rounded-full"
              style={{ background: "rgba(var(--accent-rgb),0.15)", color: "var(--accent)" }}>
              {item.category}
            </span>
          </>
        )}
      </div>

      <div className="h-px my-3" style={{ background: "var(--border)" }} />

      {/* Channel row */}
      <div className="flex items-center gap-3">
        <div className="w-9 h-9 rounded-full overflow-hidden shrink-0 flex items-center justify-center text-sm font-bold" style={{ background: "var(--deep)", color: "var(--text-primary)" }}>
          {item.channelImage
            ? <Image src={item.channelImage} alt={item.channelName} width={36} height={36} className="w-full h-full object-cover" unoptimized />
            : item.channelName[0]?.toUpperCase()
          }
        </div>
        <div className="flex-1 min-w-0">
          <p className="text-sm font-semibold truncate" style={{ color: "var(--text-primary)" }}>{item.channelName}</p>
        </div>
        <button
          onClick={toggle}
          disabled={subLoading}
          className="flex items-center gap-1.5 px-4 py-1.5 rounded-full text-xs font-bold transition-all active:scale-95 disabled:opacity-60"
          style={subscribed
            ? { background: "var(--card)", color: "#888", border: "1px solid var(--border)" }
            : { background: "var(--accent)", color: "#fff" }
          }
        >
          {subscribed ? <><Check size={11} strokeWidth={2.5} /> Subscribed</> : <><Users size={11} strokeWidth={2} /> Subscribe</>}
        </button>
      </div>

      <div className="h-px my-3" style={{ background: "var(--border)" }} />

      {/* Action buttons */}
      <div className="flex items-center gap-2 flex-wrap">
        {/* Like */}
        <button
          onClick={onLike}
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition-all active:scale-95"
          style={{
            background: liked ? "rgba(var(--accent-rgb),0.15)" : "var(--card)",
            color: liked ? "var(--accent)" : "#999",
            border: `1px solid ${liked ? "rgba(var(--accent-rgb),0.3)" : "var(--border)"}`,
          }}
        >
          <ThumbsUp size={14} fill={liked ? "var(--accent)" : "none"} strokeWidth={1.8}
            style={{ transition: "transform 0.2s cubic-bezier(0.34,1.8,0.64,1)", transform: likeAnim ? "scale(1.35)" : "scale(1)" }} />
          {totalLikes > 0 ? totalLikes.toLocaleString() : "Like"}
        </button>

        {/* Dislike */}
        <button
          onClick={handleDislike}
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition-all active:scale-95"
          style={{
            background: disliked ? "rgba(99,102,241,0.12)" : "var(--card)",
            color: disliked ? "#818cf8" : "#999",
            border: `1px solid ${disliked ? "rgba(99,102,241,0.28)" : "var(--border)"}`,
          }}
        >
          <ThumbsDown size={14} fill={disliked ? "#818cf8" : "none"} strokeWidth={1.8} />
          {totalDislikes > 0 ? totalDislikes.toLocaleString() : "Dislike"}
        </button>

        {/* Share */}
        <button
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition-all active:scale-95"
          style={{ background: copied ? "rgba(var(--accent-rgb),0.12)" : "var(--card)", color: copied ? "var(--accent)" : "#999", border: "1px solid var(--border)" }}
          onClick={() => share({ title: item.title, path: `/rent/play/${item.id}` })}
        >
          <Share2 size={14} strokeWidth={1.8} /> {copied ? "Copied!" : "Share"}
        </button>

        {/* Comments */}
        {item.canComment && (
          <button
            onClick={() => setCommentOpen(true)}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition-all active:scale-95"
            style={{
              background: commentOpen ? "rgba(99,102,241,0.1)" : "var(--card)",
              color: commentOpen ? "#818cf8" : "#999",
              border: `1px solid ${commentOpen ? "rgba(99,102,241,0.25)" : "var(--border)"}`,
            }}
          >
            <MessageCircle size={14} strokeWidth={1.8} /> Comments
          </button>
        )}

        {/* Rent badge */}
        <span className="ml-auto flex items-center gap-1 px-2.5 py-1 rounded-full text-[10px] font-black"
          style={{ background: "rgba(var(--accent-gold-rgb),0.15)", color: "var(--accent-gold)", border: "1px solid rgba(var(--accent-gold-rgb),0.25)" }}>
          ✓ Rented
        </span>
      </div>

      {/* Description */}
      {item.description && (
        <>
          <div className="h-px my-3" style={{ background: "var(--border)" }} />
          <div className="rounded-xl p-3 cursor-pointer" style={{ background: "var(--card)" }}
            onClick={() => setDescExpanded((e) => !e)}>
            <p className={`text-xs leading-relaxed whitespace-pre-line ${!descExpanded ? "line-clamp-3" : ""}`} style={{ color: "#aaa" }}>
              {item.description}
            </p>
            {item.description.length > 180 && (
              <button className="text-xs font-semibold mt-1.5" style={{ color: "var(--accent)" }}>
                {descExpanded ? "Show less" : "Show more"}
              </button>
            )}
          </div>
        </>
      )}

      {/* Comment section */}
      {item.canComment && commentOpen && (
        <CommentSection
          mode="sheet"
          isOpen={commentOpen}
          onClose={() => setCommentOpen(false)}
          contentType={item.contentType}
          contentId={item.id}
          totalComments={0}
          canComment
        />
      )}
    </div>
  );
}

/* ── main page ───────────────────────────────────────────────────────────── */

export default function RentPlayPage({ contentId }: { contentId: string }) {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const selectedItem = useAppSelector((s) => s.rent.selectedItem);
  const currentTime = useAppSelector((s) => s.player.currentTime);
  const currentTimeRef = useRef(0);
  useEffect(() => { currentTimeRef.current = currentTime; }, [currentTime]);

  // Use the Redux-stored item if it matches this contentId,
  // otherwise fall back gracefully
  const item: RentItem | null =
    selectedItem?.id === contentId ? selectedItem : null;

  useAddView(item?.contentType, item?.id);
  useAddToHistory(item?.contentType, item?.id, undefined, 5000, () => currentTimeRef.current);

  useEffect(() => {
    if (!item) return;
    dispatch(
      playMedia({
        id: item.id,
        type: getContentTypeForPlayer(item.contentType),
        title: item.title,
        thumbnail: item.thumbnail,
        channelName: item.channelName,
        videoUrl: item.videoUrl,
        videoContentUploadType: item.contentUploadType,
      }),
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [item?.id]);

  if (!item) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[60vh] gap-4">
        <Eye size={32} color="#555" strokeWidth={1.2} />
        <p className="text-sm" style={{ color: "#888" }}>Content not found</p>
        <button onClick={() => router.back()}
          className="px-5 py-2 rounded-full text-xs font-bold text-[#ffffff] active:scale-95"
          style={{ background: "var(--accent)" }}>
          Go Back
        </button>
      </div>
    );
  }

  return (
    <div className="w-full px-4 py-4 pb-24 md:pb-8">
      {/* Back button */}
      <button onClick={() => router.back()}
        className="flex items-center gap-2 mb-3 text-[12px] font-semibold transition-colors"
        style={{ color: "var(--text-muted)" }}>
        <ArrowLeft size={14} strokeWidth={2} /> Back
      </button>

      <div className="flex flex-col lg:flex-row gap-6 mx-auto">
        {/* Player + info */}
        <div className="flex-1 min-w-0 flex flex-col">
          {item.videoUrl ? (
            <VideoPlayer url={item.videoUrl} contentUploadType={item.contentUploadType} />
          ) : (
            <VideoPlayerSkeleton />
          )}
          <RentVideoInfo item={item} />
        </div>
      </div>
    </div>
  );
}
