"use client";

import moment from "moment";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { ArrowLeft } from "lucide-react";

import { wpautop } from "@/utils/wpautop";
import { AVATAR_FALLBACK, mapBlogComment } from "@/utils/mapBlogComment";
import { useAppSelector } from "@/redux/hooks";
import { IBlogPost, IBlogPostDetail } from "@/api/types/blog";

import BlogCard from "@/components/Blog/BlogCard";
import AuthorBio from "@/components/Blog/BlogDetails/AuthorBio";
import CommentsBlog from "@/components/Blog/BlogDetails/CommentsBlog";
import BlogDetail from "@/components/Blog/BlogDetails/BlogDetail";
import PaywallCard from "@/components/Membership/PaywallCard";
import SubscriptionRequiredModal from "@/components/Membership/SubscriptionRequiredModal";
import LoginModal from "@/components/Membership/LoginModal";

interface BlogDetailContentProps {
  post: IBlogPostDetail;
  morePostsRaw: IBlogPost[];
}

const BlogDetailContent = ({ post, morePostsRaw }: BlogDetailContentProps) => {
  const router = useRouter();
  const { user, isAuthenticated } = useAppSelector((state) => state.auth);
  const isSubscribed = user?.isPremium ?? false;
  const [subModalOpen, setSubModalOpen] = useState(false);
  const [loginModalOpen, setLoginModalOpen] = useState(false);

  // Full content is available to subscribers, and to any logged-in user on a
  // non-exclusive blog. Everyone else (guests, and logged-in non-subscribers on
  // exclusive blogs) sees only the limited content + paywall.
  const canViewFull = isSubscribed || (isAuthenticated && !post.isExclusive);

  const detailsHtml = wpautop(
    (canViewFull ? post.description : post.limitedContent) ?? "",
  );

  const featuredImage = post.featuredImage?.filePath ?? "";
  const authorName = post.author?.name ?? "Unknown";
  const authorAvatar = post.author?.profileImage?.filePath ?? AVATAR_FALLBACK;
  const bio = post.author?.aboutMe ?? "";
  const mappedComments = (post.comments?.data ?? []).map(mapBlogComment);
  const morePosts = morePostsRaw.filter((p) => p.id !== post.id).slice(0, 3);

  // Reading and posting comments follow the same matrix: allowed for logged-in
  // users on non-exclusive blogs, and for subscribers on exclusive blogs.
  const showComments = isAuthenticated && (isSubscribed || !post.isExclusive);
  const canPost = showComments;
  const showPaywall = !canViewFull;
  // console.log(post, "post====>");

  return (
    <div className="min-h-screen bg-white overflow-x-clip">
      <div className="max-w-282.5 mx-auto px-4 sm:px-6 py-6 sm:py-8">
        {/* Back link */}
        <Link
          href="/blog"
          className="text-sm text-blue-500 hover:underline mb-6 inline-flex items-center gap-1"
        >
          <ArrowLeft className="h-4 w-4 shrink-0" />
          Back to Blogs
        </Link>

        <div className="flex flex-col md:flex-row items-start gap-8 md:gap-10 lg:gap-20">
          {/* Main Content Area */}
          <article className="w-full flex-1 min-w-0 lg:flex-none lg:w-180 self-start flex flex-col gap-5">
            {showPaywall ? (
              <>
                {/* Clipped article content with blur on the tail end */}
                <div className="relative min-h-75 overflow-hidden">
                  <BlogDetail
                    title={post.title}
                    description={post.description ?? ""}
                    author={authorName}
                    role=""
                    date={
                      post.publishedAt
                        ? moment(post.publishedAt).format("MMMM D, YYYY")
                        : "—"
                    }
                    commentsCount={post.commentsCount}
                    featuredImage={featuredImage}
                    details={detailsHtml}
                  />

                  {/* Blur layer — bottom 220px, fading in from the top */}
                  {/* Blur layer */}
                  <div
                    aria-hidden
                    className="absolute bottom-0 left-0 right-0 h-55 pointer-events-none backdrop-blur-[5px] mask-[linear-gradient(to_bottom,transparent_0%,black_55%)] [-webkit-mask-image:linear-gradient(to_bottom,transparent_0%,black_55%)]"
                  />

                  {/* White fade */}
                  <div
                    aria-hidden
                    className="absolute bottom-0 left-0 right-0 h-27.5 pointer-events-none bg-linear-to-b from-transparent to-white"
                  />
                </div>

                <PaywallCard
                  mode={isAuthenticated ? "subscribe" : "login"}
                  onLoginClick={() => setLoginModalOpen(true)}
                  onSubscribeClick={() => setSubModalOpen(true)}
                />
              </>
            ) : (
              <BlogDetail
                title={post.title}
                description={post.description ?? ""}
                author={authorName}
                role=""
                date={
                  post.publishedAt
                    ? moment(post.publishedAt).format("MMMM D, YYYY")
                    : "—"
                }
                commentsCount={post.commentsCount}
                featuredImage={featuredImage}
                details={detailsHtml}
              />
            )}

            {/* Comments Section */}
            {showComments && (
              <CommentsBlog
                postId={post.id}
                postCode={post.code}
                postAuthorId={post.author?.id}
                commentsCount={post.commentsCount}
                comments={mappedComments}
                canPost={canPost}
                onSubscribeClick={() => setSubModalOpen(true)}
              />
            )}
          </article>

          {/* Sidebar */}
          <aside className="w-full md:w-56 xl:w-90 shrink-0 self-stretch">
            <div className="sticky top-22 flex flex-col gap-10">
              <AuthorBio
                name={authorName}
                avatar={authorAvatar}
                bio={bio}
                socialLinks={post.author?.socialMediaLinks ?? []}
              />
            </div>
          </aside>
        </div>
      </div>

      {/* More Like This (full-width) */}
      {morePosts.length > 0 && (
        <section className="bg-[#FAFAFA] py-10 sm:py-16 lg:py-17.25 px-4 sm:px-10">
          <div className="max-w-302.5 mx-auto">
            <h3 className="font-semibold mb-6 font-serif text-[#484848] text-2xl sm:text-[28px] tracking-[-0.28px] leading-[120%]">
              More like this
            </h3>
            <div className="flex flex-wrap gap-5 justify-center xl:justify-start">
              {morePosts.map((p) => (
                <BlogCard key={p.id} post={p} />
              ))}
            </div>
          </div>
        </section>
      )}

      <SubscriptionRequiredModal
        isOpen={subModalOpen}
        onClose={() => setSubModalOpen(false)}
        onViewPlans={() =>
          router.push(
            `/my-account?current-section=subscription&redirect=${encodeURIComponent(
              window.location.pathname,
            )}`,
          )
        }
      />

      <LoginModal
        isOpen={loginModalOpen}
        onClose={() => setLoginModalOpen(false)}
      />
    </div>
  );
};

export default BlogDetailContent;
