"use client";

import { useState } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { VideoDetail } from "@/services/videoDetailService";
import { useSubscribe } from "@/hooks/useSubscribe";
import { useLikeDislike } from "@/hooks/useLikeDislike";
import { useShare } from "@/hooks/useShare";
import { ContentActionsModal } from "@/components/shared/ContentActionsModal";
import { useTranslation } from "@/i18n";

interface VideoInfoProps {
  video: VideoDetail;
}

export function VideoInfo({ video }: VideoInfoProps) {
  const [descExpanded, setDescExpanded] = useState(false);
  const [actionsOpen, setActionsOpen] = useState(false);
  const router = useRouter();
  const { share, copied } = useShare();
  const { t } = useTranslation();

  const goToCreator = () => {
    if (video.channelUserId) router.push(`/profile/${video.channelUserId}`);
  };

  const { subscribed, loading: subLoading, toggle: toggleSubscribe } =
    useSubscribe(video.channelUserId, video.isSubscribe === 1);

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

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

      {/* Meta row */}
      <div className="flex items-center gap-2 mt-1.5 flex-wrap">
        <span className="text-xs" style={{ color: "var(--text-muted)" }}>{video.views}</span>
        <span style={{ color: "var(--text-muted)" }}>·</span>
        <span className="text-xs" style={{ color: "var(--text-muted)" }}>{video.uploadedAt}</span>
        {video.categoryName && (
          <>
            <span style={{ color: "var(--text-muted)" }}>·</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)" }}
            >
              {video.categoryName}
            </span>
          </>
        )}
      </div>

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

      {/* Channel row */}
      <div className="flex items-center gap-3">
        {/* Avatar — clickable */}
        <div
          className="w-9 h-9 rounded-full overflow-hidden shrink-0 flex items-center justify-center text-sm font-bold cursor-pointer transition-opacity hover:opacity-80 active:scale-95"
          style={{ color: "var(--text-primary)", background: "var(--deep)" }}
          onClick={goToCreator}
        >
          {video.channelImage ? (
            <Image
              src={video.channelImage}
              alt={video.channelName}
              width={36}
              height={36}
              className="w-full h-full object-cover"
              unoptimized
            />
          ) : (
            video.channelName[0]?.toUpperCase()
          )}
        </div>

        {/* Channel name + subscribers — clickable */}
        <div className="flex-1 min-w-0 cursor-pointer" onClick={goToCreator}>
          <p className="text-sm font-semibold truncate hover:text-orange-400 transition-colors" style={{ color: "var(--text-primary)" }}>{video.channelName}</p>
          <p className="text-[11px]" style={{ color: "var(--text-muted)" }}>
            {video.totalSubscribers.toLocaleString()} {t("video_subscribers")}
          </p>
        </div>

        {/* Subscribe button */}
        <button
          onClick={toggleSubscribe}
          disabled={subLoading}
          className="px-4 py-1.5 rounded-full text-xs font-bold transition-all duration-150 active:scale-95 disabled:opacity-60"
          style={
            subscribed
              ? { background: "var(--card)", color: "var(--text-muted)", border: "1px solid var(--border)" }
              : { background: "var(--accent)", color: "#fff" }
          }
        >
          {subLoading ? "…" : subscribed ? t("feeds_subscribed") : t("feeds_subscribe")}
        </button>
      </div>

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

      {/* Action buttons */}
      <div className="flex items-center gap-2 flex-wrap">
        {/* Like */}
        <button
          onClick={handleLike}
          disabled={likeLoading}
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition-all duration-150 active:scale-95 disabled:opacity-70"
          style={{
            background: liked ? "rgba(var(--accent-rgb),0.15)" : "var(--card)",
            color: liked ? "var(--accent)" : "var(--text-muted)",
            border: `1px solid ${liked ? "rgba(var(--accent-rgb),0.3)" : "var(--border)"}`,
          }}
        >
          <svg width="14" height="14" viewBox="0 0 24 24"
            fill={liked ? "var(--accent)" : "none"}
            stroke={liked ? "var(--accent)" : "currentColor"}
            strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"
          >
            <path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3H14z" />
            <path d="M7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3" />
          </svg>
          {totalLikes.toLocaleString()}
        </button>

        {/* Dislike */}
        <button
          onClick={handleDislike}
          disabled={likeLoading}
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition-all duration-150 active:scale-95 disabled:opacity-70"
          style={{
            background: disliked ? "rgba(99,102,241,0.12)" : "var(--card)",
            color: disliked ? "#818cf8" : "var(--text-muted)",
            border: `1px solid ${disliked ? "rgba(99,102,241,0.28)" : "var(--border)"}`,
          }}
        >
          <svg width="14" height="14" viewBox="0 0 24 24"
            fill={disliked ? "#818cf8" : "none"}
            stroke={disliked ? "#818cf8" : "currentColor"}
            strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"
          >
            <path d="M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3H10z" />
            <path d="M17 2h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17" />
          </svg>
          {totalDislikes.toLocaleString()}
        </button>

        {/* Share */}
        <button
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition-all duration-150 active:scale-95"
          style={{ background: copied ? "rgba(var(--accent-rgb),0.12)" : "var(--card)", color: copied ? "var(--accent)" : "var(--text-muted)", border: "1px solid var(--border)" }}
          onClick={() => share({ title: video.title, path: `/video/${video.id}` })}
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"
          >
            <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8" />
            <polyline points="16 6 12 2 8 6" />
            <line x1="12" y1="2" x2="12" y2="15" />
          </svg>
          {copied ? t("feeds_copied") : t("feeds_share")}
        </button>

        {/* Download (if allowed) */}
        {video.isDownload === 1 && (
          <button
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition-all duration-150 active:scale-95"
            style={{ background: "var(--card)", color: "var(--text-muted)", border: "1px solid var(--border)" }}
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
              stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"
            >
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
              <polyline points="7 10 12 15 17 10" />
              <line x1="12" y1="15" x2="12" y2="3" />
            </svg>
            {t("video_download")}
          </button>
        )}

        {/* More actions (Watch Later, Playlist, Report) */}
        <button
          onClick={() => setActionsOpen(true)}
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold transition-all duration-150 active:scale-95"
          style={{ background: "var(--card)", color: "var(--text-muted)", border: "1px solid var(--border)" }}
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
            <circle cx="12" cy="5" r="1.5" /><circle cx="12" cy="12" r="1.5" /><circle cx="12" cy="19" r="1.5" />
          </svg>
          {t("video_more")}
        </button>
      </div>

      {actionsOpen && (
        <ContentActionsModal
          context={{
            contentId:     video.id,
            contentType:   video.contentType,
            channelId:     video.channelId,
            channelUserId: video.channelUserId,
            title:         video.title,
            thumbnail:     video.thumbnail,
            channelName:   video.channelName,
          }}
          onClose={() => setActionsOpen(false)}
        />
      )}

      {/* Description */}
      {video.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: "var(--text-muted)" }}
            >
              {video.description}
            </p>
            {video.description.length > 180 && (
              <button
                className="text-xs font-semibold mt-1.5"
                style={{ color: "var(--accent)" }}
              >
                {descExpanded ? t("video_showLess") : t("video_showMore")}
              </button>
            )}
          </div>
        </>
      )}

      {/* Comment count */}
      <div className="h-px my-3" style={{ background: "var(--border)" }} />
      <div className="flex items-center gap-2">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none"
          stroke="var(--text-muted)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"
        >
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
        </svg>
        <span className="text-sm font-semibold" style={{ color: "var(--text-primary)" }}>
          {video.totalComment.toLocaleString()}
        </span>
        <span className="text-xs" style={{ color: "var(--text-muted)" }}>{t("feeds_comments")}</span>
      </div>
    </div>
  );
}

/* ── Skeleton ─────────────────────────────────────────────────────────────── */

export function VideoInfoSkeleton() {
  return (
    <div className="flex flex-col gap-3 mt-3">
      {/* Title */}
      <div className="h-5 rounded-full animate-pulse" style={{ background: "var(--card)", width: "88%" }} />
      <div className="h-5 rounded-full animate-pulse" style={{ background: "var(--card)", width: "60%" }} />
      {/* Meta */}
      <div className="flex gap-2">
        <div className="h-3 w-20 rounded-full animate-pulse" style={{ background: "var(--card)" }} />
        <div className="h-3 w-16 rounded-full animate-pulse" style={{ background: "var(--card)" }} />
      </div>
      <div className="h-px" style={{ background: "var(--border)" }} />
      {/* Channel */}
      <div className="flex items-center gap-3">
        <div className="w-9 h-9 rounded-full animate-pulse" style={{ background: "var(--card)" }} />
        <div className="flex-1 flex flex-col gap-1.5">
          <div className="h-3.5 rounded-full animate-pulse" style={{ background: "var(--card)", width: "40%" }} />
          <div className="h-2.5 rounded-full animate-pulse" style={{ background: "var(--card)", width: "25%" }} />
        </div>
        <div className="h-7 w-20 rounded-full animate-pulse" style={{ background: "var(--card)" }} />
      </div>
      <div className="h-px" style={{ background: "var(--border)" }} />
      {/* Action buttons */}
      <div className="flex gap-2">
        {[80, 64, 72, 88].map((w, i) => (
          <div key={i} className="h-8 rounded-full animate-pulse" style={{ background: "var(--card)", width: w }} />
        ))}
      </div>
    </div>
  );
}
