"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import {
  ArrowLeft, Heart, MessageCircle, Share2,
  BadgeCheck, Send, Loader2, ChevronLeft, ChevronRight,
  AlertCircle, Rss,
} from "lucide-react";
import { feedService, FeedPost, FeedComment, FeedMediaItem } from "@/services/feedService";
import { useSubscribe } from "@/hooks/useSubscribe";
import { useShare } from "@/hooks/useShare";
import Cookies from "js-cookie";

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

const NO_IMG = "no_img.png";
function isRealImg(url?: string) {
  return !!url && !url.includes(NO_IMG) && url.startsWith("http");
}

/* ── Media carousel ──────────────────────────────────────────────────────── */

function MediaCarousel({ media, tall }: { media: FeedMediaItem[]; tall?: boolean }) {
  const [idx, setIdx] = useState(0);
  const n = media.length;
  const prev = useCallback(() => setIdx((i) => (i - 1 + n) % n), [n]);
  const next = useCallback(() => setIdx((i) => (i + 1) % n), [n]);
  const cur = media[idx];
  if (!cur) return null;

  // When tall, the outer wrapper must also be 100% so the height chain reaches Image fill
  const outerH = tall ? "100%" : "auto";
  const innerH = tall ? "100%" : "min(260px, 70vw)";

  return (
    <div
      className="relative w-full overflow-hidden"
      style={{ background: "var(--deep)", height: outerH }}
    >
      <div
        className="relative w-full"
        style={{ height: innerH, minHeight: tall ? 0 : 160 }}
      >
        {cur.type === "video" && cur.video ? (
          <video
            src={cur.video}
            controls
            playsInline
            className="absolute inset-0 w-full h-full"
            style={{ objectFit: "contain", background: "#000" }}
          />
        ) : isRealImg(cur.image) ? (
          <Image
            src={cur.image}
            alt=""
            fill
            className="object-cover"
            unoptimized
            sizes="(max-width: 640px) 100vw, 600px"
            priority
          />
        ) : (
          <div className="absolute inset-0 flex flex-col items-center justify-center gap-2">
            <Rss size={28} style={{ color: "rgba(var(--accent-rgb),0.25)" }} strokeWidth={1.2} />
            <span className="text-[10px]" style={{ color: "#555" }}>No image</span>
          </div>
        )}

        {/* Subtle vignette */}
        <div
          className="absolute inset-0 pointer-events-none"
          style={{ boxShadow: "inset 0 0 40px rgba(0,0,0,0.35)" }}
        />
      </div>

      {/* Prev / Next arrows */}
      {n > 1 && (
        <>
          <button
            onClick={prev}
            className="absolute left-2.5 top-1/2 -translate-y-1/2 w-7 h-7 rounded-full flex items-center justify-center transition-all active:scale-90"
            style={{ background: "rgba(0,0,0,0.6)", backdropFilter: "blur(8px)", border: "1px solid rgba(255,255,255,0.15)" }}
          >
            <ChevronLeft size={14} color="#fff" strokeWidth={2.2} />
          </button>
          <button
            onClick={next}
            className="absolute right-2.5 top-1/2 -translate-y-1/2 w-7 h-7 rounded-full flex items-center justify-center transition-all active:scale-90"
            style={{ background: "rgba(0,0,0,0.6)", backdropFilter: "blur(8px)", border: "1px solid rgba(255,255,255,0.15)" }}
          >
            <ChevronRight size={14} color="#fff" strokeWidth={2.2} />
          </button>

          {/* Dot strip */}
          <div className="absolute bottom-2.5 left-0 right-0 flex justify-center gap-1.5">
            {Array.from({ length: n }).map((_, i) => (
              <button
                key={i}
                onClick={() => setIdx(i)}
                style={{
                  width: i === idx ? 16 : 4,
                  height: 4,
                  borderRadius: 99,
                  background: i === idx ? "#fff" : "rgba(255,255,255,0.3)",
                  border: "none",
                  cursor: "pointer",
                  padding: 0,
                  transition: "width 0.2s ease, background 0.2s ease",
                }}
              />
            ))}
          </div>

          {/* Counter pill */}
          <div
            className="absolute top-2.5 right-2.5 text-[10px] font-bold px-2 py-0.5 rounded-full"
            style={{ background: "rgba(0,0,0,0.6)", color: "rgba(255,255,255,0.7)", backdropFilter: "blur(8px)" }}
          >
            {idx + 1}/{n}
          </div>
        </>
      )}
    </div>
  );
}

/* ── Comment bubble ──────────────────────────────────────────────────────── */

function CommentRow({ c, delay = 0 }: { c: FeedComment; delay?: number }) {
  return (
    <div
      className="flex items-start gap-2.5"
      style={{ animation: `fd-up 0.32s ease both`, animationDelay: `${delay}ms` }}
    >
      <div
        className="w-7 h-7 rounded-full shrink-0 overflow-hidden flex items-center justify-center text-[10px] font-black"
        style={{ background: "var(--deep)", border: "1px solid var(--border)", marginTop: 2, color: "var(--text-primary)" }}
      >
        {c.avatar
          // eslint-disable-next-line @next/next/no-img-element
          ? <img src={c.avatar} alt="" className="w-full h-full object-cover" />
          : (c.channelName[0] || "U").toUpperCase()
        }
      </div>
      <div className="flex-1 min-w-0">
        <div
          className="rounded-2xl rounded-tl-sm px-3 py-2"
          style={{ background: "var(--card)", border: "1px solid var(--border-soft)" }}
        >
          <div className="flex items-center gap-1.5 mb-0.5">
            <span className="text-[11px] font-bold" style={{ color: "var(--text-primary)" }}>{c.channelName}</span>
            <span className="text-[10px]" style={{ color: "#444" }}>·</span>
            <span className="text-[10px]" style={{ color: "#555" }}>{c.createdAt}</span>
          </div>
          <p className="text-[12px] leading-snug" style={{ color: "var(--text-muted)" }}>
            {c.comment}
          </p>
        </div>
      </div>
    </div>
  );
}

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

function Skeleton() {
  return (
    <div style={{ background: "var(--bg)", minHeight: "100vh" }}>
      <div style={{ height: 52, background: "rgba(10,10,10,0.95)", borderBottom: "1px solid rgba(255,255,255,0.04)" }} />
      <div className="max-w-6xl mx-auto px-4 pt-4 animate-pulse">
        <div className="flex flex-col md:flex-row gap-6">
          {/* left — media */}
          <div className="md:flex-1">
            <div className="rounded-2xl" style={{ height: 280, background: "var(--card)" }} />
          </div>
          {/* right — content */}
          <div className="md:w-80 lg:w-96 flex flex-col gap-3">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full shrink-0" style={{ background: "var(--card)" }} />
              <div className="flex-1 flex flex-col gap-1.5">
                <div className="h-3 rounded-full w-28" style={{ background: "var(--card)" }} />
                <div className="h-2 rounded-full w-16" style={{ background: "var(--card)" }} />
              </div>
            </div>
            <div className="h-4 rounded-full w-4/5 mt-2" style={{ background: "var(--card)" }} />
            <div className="h-3 rounded-full w-full" style={{ background: "var(--card)" }} />
            <div className="h-3 rounded-full w-3/4" style={{ background: "var(--card)" }} />
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Main ─────────────────────────────────────────────────────────────────── */

export default function FeedDetailPage({ feedId }: { feedId: string }) {
  const router = useRouter();
  const commentInputRef = useRef<HTMLInputElement>(null);
  const [post, setPost] = useState<FeedPost | null>(null);
  const [comments, setComments] = useState<FeedComment[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [liked, setLiked] = useState(false);
  const [likeCount, setLikeCount] = useState(0);
  const [commentText, setCommentText] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [likeAnim, setLikeAnim] = useState(false);
  const myUserId = Cookies.get("user_id") ?? "";
  const { share, copied } = useShare();

  useEffect(() => {
    setLoading(true);
    feedService
      .getFeedDetail(feedId)
      .then((detail) => {
        // Accept status 200 or 1 (both are success across this API)
        const ok = detail.status === 200 || detail.status === 1;
        if (!ok || !detail.result) throw new Error("Not found");

        const raw = Array.isArray(detail.result) ? detail.result[0] : detail.result;
        if (!raw) throw new Error("Not found");

        const mapped = feedService.mapPost(raw);
        setPost(mapped);
        setLiked(mapped.isLiked);
        setLikeCount(mapped.totalLikes);

        // Load comments separately — failure here must NOT block the post
        feedService
          .getFeedComments(feedId)
          .then(setComments)
          .catch(() => {}); // comments are non-fatal
      })
      .catch(() => setError("Could not load this post."))
      .finally(() => setLoading(false));
  }, [feedId]);

  const { subscribed, loading: subLoading, toggle: toggleSub } = useSubscribe(
    post?.userId ?? "",
    post?.isSubscriber ?? false,
    post?.userType ?? 1,
  );

  const handleLike = async () => {
    if (!liked) { setLikeAnim(true); setTimeout(() => setLikeAnim(false), 500); }
    setLiked((v) => !v);
    setLikeCount((n) => (liked ? n - 1 : n + 1));
    try { await feedService.likeUnlikeFeed(feedId); }
    catch { setLiked((v) => !v); setLikeCount((n) => (liked ? n + 1 : n - 1)); }
  };

  const handleComment = async () => {
    if (!commentText.trim() || submitting) return;
    setSubmitting(true);
    const opt: FeedComment = {
      id: `opt-${Date.now()}`, feedId, userId: myUserId, parentId: "0",
      channelName: "You", avatar: "", comment: commentText.trim(),
      createdAt: "just now", totalReply: 0,
    };
    setComments((c) => [opt, ...c]);
    setCommentText("");
    try { await feedService.addFeedComment({ feedId, comment: opt.comment }); }
    catch { setComments((c) => c.filter((x) => x.id !== opt.id)); }
    setSubmitting(false);
  };

  const sharePost = () => {
    if (!post) return;
    share({ title: post.title || post.channelName || "Post", path: `/feed/${post.id} ${post.channelName}` });
  };

  if (loading) return <Skeleton />;

  if (error || !post) {
    return (
      <div className="flex flex-col items-center justify-center gap-3" style={{ minHeight: "80vh", background: "var(--bg)" }}>
        <AlertCircle size={28} color="#555" strokeWidth={1.3} />
        <p className="text-sm" style={{ color: "#666" }}>{error || "Post not found"}</p>
        <button onClick={() => router.back()} className="px-5 py-2 rounded-full text-xs font-bold text-[#ffffff]" style={{ background: "var(--accent)" }}>
          Go Back
        </button>
      </div>
    );
  }

  // Show all media items — carousel handles no_img placeholders internally
  const visibleMedia = post.media;
  const topComments = comments.filter((c) => c.parentId === "0");

  return (
    <div style={{ minHeight: "100vh", background: "var(--bg)", paddingBottom: 80 }}>

      {/* ── Sticky nav ──────────────────────────────────────────────────── */}
      <div
        className="sticky top-0 z-30 flex items-center gap-3 px-4 md:px-6"
        style={{
          height: 52,
          background: "var(--deep, #0d0d0d)",
          borderBottom: "1px solid var(--border)",
        }}
      >
        <button
          onClick={() => router.back()}
          className="w-8 h-8 rounded-full flex items-center justify-center transition-all active:scale-90 hover:brightness-125"
          style={{ background: "var(--border)", border: "1px solid var(--sheet-handle)" }}
        >
          <ArrowLeft size={15} color="#fff" strokeWidth={2.2} />
        </button>
        <span className="flex-1 text-[13px] font-bold truncate" style={{ color: "var(--text-primary)" }}>
          {post.title || post.channelName}
        </span>
        <button
          onClick={sharePost}
          className="w-8 h-8 rounded-full flex items-center justify-center transition-all active:scale-90"
          style={{
            background: copied ? "rgba(var(--accent-rgb),0.14)" : "var(--btn-ghost-hover)",
            border: `1px solid ${copied ? "rgba(var(--accent-rgb),0.35)" : "var(--border)"}`,
          }}
        >
          <Share2 size={14} color={copied ? "var(--accent)" : "#888"} strokeWidth={2} />
        </button>
      </div>

      {/* ── Responsive grid ─────────────────────────────────────────────── */}
      {/*
          Mobile  (<768px) : single column, stacked
          Tablet  (≥768px) : two columns — media left (sticky), info right
          Desktop (≥1280px): wider columns, more breathing room
      */}
      <div className="max-w-6xl mx-auto md:flex md:gap-0 md:items-start">

        {/* ══ LEFT — Media ════════════════════════════════════════════ */}
        {/* Mobile: stacked above content, natural height
            Tablet+: sticky left column, fills viewport height         */}
        <div className="md:sticky md:flex-1 md:self-start" style={{ top: 52 }}>

          {/* ── Mobile (< 768px): natural height carousel ── */}
          <div className="block md:hidden" style={{ background: "var(--deep)" }}>
            {visibleMedia.length > 0
              ? <MediaCarousel media={visibleMedia} />
              : <div className="flex items-center justify-center" style={{ height: 200 }}>
                  <Rss size={32} style={{ color: "rgba(var(--accent-rgb),0.15)" }} strokeWidth={1} />
                </div>
            }
          </div>

          {/* ── Tablet+ (≥ 768px): fills viewport minus nav ── */}
          <div
            className="hidden md:block overflow-hidden"
            style={{
              background: "var(--deep)",
              height: "calc(100vh - 52px)",   /* explicit — no Tailwind calc class */
              animation: "fd-fade 0.4s ease both",
            }}
          >
            {visibleMedia.length > 0
              ? <MediaCarousel media={visibleMedia} tall />
              : <div className="flex items-center justify-center h-full">
                  <Rss size={36} style={{ color: "rgba(var(--accent-rgb),0.15)" }} strokeWidth={1} />
                </div>
            }
          </div>
        </div>

        {/* ══ RIGHT — Content + comments ═══════════════════════════════ */}
        <div
          className="md:w-80 lg:w-96 xl:w-[420px] shrink-0 flex flex-col"
          style={{
            borderLeft: "1px solid var(--border-soft)",
            animation: "fd-up 0.4s ease both",
          }}
        >
          {/* Author row */}
          <div
            className="flex items-center justify-between px-4 py-3.5"
            style={{ borderBottom: "1px solid var(--border-soft)" }}
          >
            <div className="flex items-center gap-2.5">
              <div
                className="relative w-9 h-9 rounded-full overflow-hidden shrink-0 flex items-center justify-center text-sm font-black"
                style={{
                  background: "var(--card)",
                  border: "2px solid rgba(var(--accent-rgb),0.35)",
                  color: "var(--accent)",
                }}
              >
                {isRealImg(post.profileImg) ? (
                  <Image src={post.profileImg} alt={post.channelName} fill className="object-cover" unoptimized sizes="36px" />
                ) : (
                  post.channelName[0]?.toUpperCase()
                )}
              </div>
              <div>
                <div className="flex items-center gap-1">
                  <span className="text-[13px] font-black leading-none" style={{ color: "var(--text-primary)" }}>{post.channelName}</span>
                  {post.isVerified && <BadgeCheck size={12} style={{ color: "var(--accent)" }} />}
                </div>
                <span className="text-[10px]" style={{ color: "#555" }}>{post.createdAt}</span>
              </div>
            </div>
            <button
              onClick={toggleSub}
              disabled={subLoading}
              className="text-[10px] font-black px-3 py-1.5 rounded-full transition-all active:scale-95 disabled:opacity-40"
              style={subscribed
                ? { background: "var(--btn-ghost)", color: "#666", border: "1px solid var(--border)" }
                : { background: "rgba(var(--accent-rgb),0.1)", color: "var(--accent)", border: "1px solid rgba(var(--accent-rgb),0.25)" }
              }
            >
              {subLoading ? "…" : subscribed ? "Following" : "Follow"}
            </button>
          </div>

          {/* Title + description + hashtags */}
          <div
            className="px-4 py-3 flex-1"
            style={{
              overflowY: "auto",
              animation: "fd-up 0.42s ease both 0.08s",
            }}
          >
            {post.title && (
              <h1
                className="mb-2 leading-snug"
                style={{ fontSize: 14, fontWeight: 800, letterSpacing: "-0.015em", color: "var(--text-primary)" }}
              >
                {post.title}
              </h1>
            )}
            {post.description && (
              <p
                className="leading-relaxed mb-3"
                style={{ fontSize: 12, color: "var(--text-muted)", whiteSpace: "pre-line" }}
              >
                {post.description}
              </p>
            )}
            {post.hashtags.length > 0 && (
              <div className="flex flex-wrap gap-1.5 mb-2">
                {post.hashtags.map((h) => (
                  <span
                    key={h.id}
                    className="text-[10px] font-bold px-2 py-0.5 rounded-full"
                    style={{ background: "rgba(var(--accent-rgb),0.09)", color: "var(--accent)", border: "1px solid rgba(var(--accent-rgb),0.18)" }}
                  >
                    #{h.name}
                  </span>
                ))}
              </div>
            )}
            {likeCount > 0 && (
              <div className="flex items-center gap-1.5 mt-1">
                <Heart size={10} fill="var(--accent)" strokeWidth={0} />
                <span className="text-[10px] font-semibold" style={{ color: "var(--text-muted)" }}>
                  {likeCount.toLocaleString()} {likeCount === 1 ? "like" : "likes"}
                </span>
              </div>
            )}
          </div>

          {/* Divider */}
          <div style={{ height: 1, background: "var(--border-soft)" }} />

          {/* Action strip */}
          <div
            className="flex items-center px-2 py-1"
            style={{ animation: "fd-up 0.44s ease both 0.1s", borderBottom: "1px solid var(--border-soft)" }}
          >
            <button
              onClick={handleLike}
              className="flex items-center gap-1.5 py-2.5 rounded-xl transition-all active:scale-95 flex-1 justify-center"
              style={{ color: liked ? "var(--accent)" : "#666" }}
            >
              <Heart
                size={17}
                fill={liked ? "var(--accent)" : "none"}
                strokeWidth={liked ? 0 : 1.8}
                style={{ transition: "transform 0.22s cubic-bezier(0.34,1.9,0.64,1)", transform: likeAnim ? "scale(1.5)" : "scale(1)" }}
              />
              <span className="text-[11px] font-bold">{liked ? "Liked" : "Like"}</span>
            </button>
            <div style={{ width: 1, height: 16, background: "var(--border)" }} />
            <button
              onClick={() => setTimeout(() => commentInputRef.current?.focus(), 50)}
              className="flex items-center gap-1.5 py-2.5 rounded-xl transition-all active:scale-95 flex-1 justify-center"
              style={{ color: "#666" }}
            >
              <MessageCircle size={17} strokeWidth={1.8} />
              <span className="text-[11px] font-bold">{topComments.length > 0 ? topComments.length : "Comment"}</span>
            </button>
            <div style={{ width: 1, height: 16, background: "var(--border)" }} />
            <button
              onClick={sharePost}
              className="flex items-center gap-1.5 py-2.5 rounded-xl transition-all active:scale-95 flex-1 justify-center"
              style={{ color: copied ? "var(--accent)" : "#666" }}
            >
              <Share2 size={17} strokeWidth={1.8} color={copied ? "var(--accent)" : undefined} />
              <span className="text-[11px] font-bold">{copied ? "Copied!" : "Share"}</span>
            </button>
          </div>

          {/* Comments */}
          <div
            className="px-4 pt-3 pb-6"
            style={{ animation: "fd-up 0.48s ease both 0.13s" }}
          >
            <p className="text-[10px] font-black uppercase tracking-[0.12em] mb-3" style={{ color: "#444" }}>
              {topComments.length > 0 ? `${topComments.length} Comment${topComments.length !== 1 ? "s" : ""}` : "Comments"}
            </p>

            {/* Comment input */}
            <div
              className="flex items-center gap-2.5 mb-4 px-3 py-2.5 rounded-2xl"
              style={{ background: "var(--card)", border: "1px solid var(--border)" }}
            >
              <input
                ref={commentInputRef}
                className="flex-1 bg-transparent outline-none placeholder:text-[#444]"
                style={{ color: "var(--text-primary)", fontSize: 12 }}
                placeholder="Write a comment…"
                value={commentText}
                onChange={(e) => setCommentText(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter") handleComment(); }}
              />
              <button onClick={handleComment} disabled={!commentText.trim() || submitting} className="transition-all active:scale-90 disabled:opacity-20">
                {submitting
                  ? <Loader2 size={14} className="animate-spin" color="var(--accent)" />
                  : <Send size={14} color={commentText.trim() ? "var(--accent)" : "#444"} strokeWidth={2} />
                }
              </button>
            </div>

            {/* List */}
            {topComments.length === 0 ? (
              <p className="text-center py-6 text-[11px]" style={{ color: "#444" }}>Be the first to comment</p>
            ) : (
              <div className="flex flex-col gap-3">
                {topComments.map((c, i) => <CommentRow key={c.id} c={c} delay={i * 40} />)}
              </div>
            )}
          </div>
        </div>
      </div>

      <style>{`
        @keyframes fd-up   { from { opacity:0; transform:translateY(14px); } to { opacity:1; transform:translateY(0); } }
        @keyframes fd-fade { from { opacity:0; } to { opacity:1; } }
      `}</style>
    </div>
  );
}
