"use client";

import React, { useState, useEffect, useRef, useCallback } from "react";
import {
  ArrowLeft,
  Calendar,
  Tag,
  Download,
  Share2,
  Film,
  Sparkles,
  Tv,
  Image as ImageIcon,
  Check,
  RefreshCw,
  ExternalLink,
  ShieldCheck,
  Zap,
} from "lucide-react";
import { PostContent } from "../types";
import { getPost, isMdriveLink } from "../services/scraper";
import { DownloadModal } from "./DownloadModal";
import { getSiteName } from "../config/site";

interface PostPageProps {
  slug: string;
  fallbackTitle?: string;
  fallbackImage?: string;
  onBack: () => void;
}

export function PostPage({
  slug,
  fallbackTitle = "",
  fallbackImage = "",
  onBack,
}: PostPageProps) {
  const [post, setPost] = useState<PostContent | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);

  // Download modal state
  const [activeDownloadUrl, setActiveDownloadUrl] = useState<string | null>(null);
  const [activeDownloadLabel, setActiveDownloadLabel] = useState<string>("");

  // Screenshot lightbox
  const [lightboxImage, setLightboxImage] = useState<string | null>(null);

  const bodyRef = useRef<HTMLDivElement>(null);

  const loadPostData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await getPost(slug);
      setPost(data);

      // Update document title for SEO
      if (data.title) {
        document.title = `${data.title} — ${getSiteName()}`;
      }
    } catch (err: any) {
      setError(err?.message || "Failed to load movie details. Please try again.");
    } finally {
      setLoading(false);
    }
  }, [slug]);

  useEffect(() => {
    let isMounted = true;

    async function init() {
      setLoading(true);
      setError(null);
      try {
        const data = await getPost(slug);
        if (!isMounted) return;
        setPost(data);

        if (data.title) {
          document.title = `${data.title} — ${getSiteName()}`;
        }
      } catch (err: any) {
        if (!isMounted) return;
        setError(err?.message || "Failed to load movie details. Please try again.");
      } finally {
        if (isMounted) setLoading(false);
      }
    }

    init();
    window.scrollTo({ top: 0, behavior: "smooth" });

    return () => {
      isMounted = false;
    };
  }, [slug]);

  // Intercept any click on download links inside dynamically rendered body HTML
  useEffect(() => {
    if (!bodyRef.current || !post) return;

    const handleBodyClick = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      const anchor = target.closest("a");
      if (!anchor) return;

      const href = anchor.getAttribute("href") || "";
      const text = (anchor.textContent || "").trim();

      // If it looks like a download link or mdrive link, intercept and show modal
      if (
        isMdriveLink(href) ||
        /480p|720p|1080p|2160p|4K|HEVC|Download|G-Drive|Fast/i.test(`${text} ${href}`)
      ) {
        e.preventDefault();
        e.stopPropagation();
        setActiveDownloadUrl(href);
        setActiveDownloadLabel(text || "Download Link");
      }
    };

    const el = bodyRef.current;
    el.addEventListener("click", handleBodyClick);
    return () => {
      el.removeEventListener("click", handleBodyClick);
    };
  }, [post]);

  const handleShare = async () => {
    const shareUrl = typeof window !== "undefined" ? window.location.href : "";
    const shareTitle = post?.title || fallbackTitle || "PK Movies";

    if (navigator.share) {
      try {
        await navigator.share({
          title: shareTitle,
          url: shareUrl,
        });
        return;
      } catch {
        // Fallback to clipboard
      }
    }

    if (navigator.clipboard) {
      await navigator.clipboard.writeText(shareUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2500);
    }
  };

  const handleDownloadClick = (url: string, label: string) => {
    setActiveDownloadUrl(url);
    setActiveDownloadLabel(label);
  };

  const title = post?.title || fallbackTitle || slug.replace(/-/g, " ");
  const posterImage = post?.imageUrl || fallbackImage;

  return (
    <div id="post-page-container" className="w-full max-w-5xl mx-auto px-3 sm:px-6 py-6 space-y-8 animate-in fade-in duration-300">
      {/* Top Navigation Bar */}
      <div className="flex items-center justify-between gap-4">
        <button
          id="post-back-button"
          onClick={onBack}
          className="flex items-center gap-2 px-4 py-2.5 rounded-xl bg-white/[0.04] hover:bg-white/[0.08] text-white/80 hover:text-white border border-white/10 transition-colors text-xs font-semibold group"
        >
          <ArrowLeft className="w-4 h-4 group-hover:-translate-x-0.5 transition-transform" />
          <span>Back to Movies</span>
        </button>

        <button
          id="post-share-button"
          onClick={handleShare}
          className="flex items-center gap-2 px-4 py-2.5 rounded-xl bg-white/[0.04] hover:bg-white/[0.08] text-white/80 hover:text-white border border-white/10 transition-colors text-xs font-semibold"
        >
          {copied ? (
            <>
              <Check className="w-4 h-4 text-emerald-400" />
              <span className="text-emerald-400">Copied Link</span>
            </>
          ) : (
            <>
              <Share2 className="w-4 h-4" />
              <span>Share Movie</span>
            </>
          )}
        </button>
      </div>

      {/* Loading state */}
      {loading && !post && (
        <div className="space-y-6 animate-pulse">
          <div className="flex flex-col md:flex-row gap-6 p-6 rounded-3xl bg-white/[0.03] border border-white/10">
            <div className="w-full md:w-64 aspect-[2/3] rounded-2xl bg-white/10 shrink-0" />
            <div className="flex-1 space-y-4 py-2">
              <div className="h-8 w-3/4 bg-white/15 rounded-lg" />
              <div className="h-4 w-1/3 bg-white/10 rounded-lg" />
              <div className="h-24 w-full bg-white/5 rounded-xl" />
              <div className="h-12 w-48 bg-red-600/40 rounded-xl" />
            </div>
          </div>
        </div>
      )}

      {/* Error state */}
      {error && !post && (
        <div className="flex flex-col items-center justify-center p-8 sm:p-12 rounded-3xl bg-red-950/20 border border-red-500/30 text-center space-y-4">
          <div className="w-12 h-12 rounded-2xl bg-red-600/20 text-red-400 flex items-center justify-center">
            <RefreshCw className="w-6 h-6" />
          </div>
          <div className="space-y-1 max-w-md">
            <h3 className="text-lg font-bold text-white">Failed to Load Content</h3>
            <p className="text-xs text-white/60">{error}</p>
          </div>
          <button
            onClick={loadPostData}
            className="flex items-center gap-2 px-6 py-3 rounded-xl bg-red-600 hover:bg-red-500 text-white font-bold text-xs transition-all shadow-lg"
          >
            <RefreshCw className="w-4 h-4" />
            <span>Try Again</span>
          </button>
        </div>
      )}

      {/* Post Content */}
      {post && (
        <div className="space-y-8">
          {/* Main Hero Card */}
          <div className="relative overflow-hidden rounded-3xl bg-neutral-950/90 border border-white/10 p-6 sm:p-8 shadow-2xl">
            {/* Ambient Background Glow */}
            <div className="absolute top-0 right-0 w-96 h-96 bg-red-600/10 blur-[120px] pointer-events-none rounded-full" />

            <div className="flex flex-col md:flex-row gap-6 sm:gap-8 relative z-10">
              {/* Poster Image */}
              <div className="w-full sm:w-64 md:w-72 shrink-0 mx-auto md:mx-0">
                <div className="relative rounded-2xl overflow-hidden aspect-[2/3] bg-neutral-900 border border-white/15 shadow-2xl">
                  {posterImage ? (
                    <img
                      src={posterImage}
                      alt={title}
                      className="w-full h-full object-cover"
                    />
                  ) : (
                    <div className="w-full h-full flex flex-col items-center justify-center text-white/40">
                      <Film className="w-12 h-12 text-red-500/50 mb-2" />
                      <span className="text-xs">No Poster</span>
                    </div>
                  )}
                  <div className="absolute top-3 left-3">
                    <span className="inline-flex items-center gap-1 px-3 py-1 rounded-full text-[11px] font-bold uppercase tracking-wider bg-red-600 text-white shadow-md">
                      <Sparkles className="w-3 h-3" />
                      HD / 4K
                    </span>
                  </div>
                </div>
              </div>

              {/* Title & Metadata */}
              <div className="flex-1 flex flex-col justify-between space-y-4">
                <div className="space-y-3">
                  <h1 className="text-2xl sm:text-3xl md:text-4xl font-extrabold text-white tracking-tight leading-snug">
                    {title}
                  </h1>

                  {/* Date & Categories */}
                  <div className="flex items-center gap-4 flex-wrap text-xs text-white/60">
                    {post.date && (
                      <span className="flex items-center gap-1.5 bg-white/[0.04] px-3 py-1.5 rounded-lg border border-white/5">
                        <Calendar className="w-3.5 h-3.5 text-red-400" />
                        <span>{post.date}</span>
                      </span>
                    )}

                    {post.categories.length > 0 && (
                      <div className="flex items-center gap-1.5 flex-wrap">
                        <Tag className="w-3.5 h-3.5 text-white/40" />
                        {post.categories.map((cat, idx) => (
                          <span
                            key={idx}
                            className="bg-white/[0.04] text-white/80 px-2.5 py-1 rounded-lg border border-white/5 text-[11px] font-medium"
                          >
                            {cat.name}
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                </div>

                {/* Quick Trust Badges */}
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-2.5 py-2">
                  <div className="flex items-center gap-2 p-2.5 rounded-xl bg-white/[0.02] border border-white/5">
                    <ShieldCheck className="w-4 h-4 text-emerald-400 shrink-0" />
                    <span className="text-[11px] text-white/70 font-medium">Virus Scanned</span>
                  </div>
                  <div className="flex items-center gap-2 p-2.5 rounded-xl bg-white/[0.02] border border-white/5">
                    <Zap className="w-4 h-4 text-amber-400 shrink-0" />
                    <span className="text-[11px] text-white/70 font-medium">High Speed Links</span>
                  </div>
                  <div className="flex items-center gap-2 p-2.5 rounded-xl bg-white/[0.02] border border-white/5 col-span-2 sm:col-span-1">
                    <Tv className="w-4 h-4 text-sky-400 shrink-0" />
                    <span className="text-[11px] text-white/70 font-medium">All Qualities</span>
                  </div>
                </div>

                {/* Jump to Download CTA */}
                <div className="pt-2">
                  <a
                    href="#download-links-section"
                    className="inline-flex items-center gap-2.5 px-6 py-3.5 rounded-2xl bg-red-600 hover:bg-red-500 text-white font-bold text-sm shadow-xl shadow-red-600/30 hover:shadow-red-600/50 hover:scale-105 active:scale-95 transition-all border border-red-400/40"
                  >
                    <Download className="w-4 h-4" />
                    <span>Download Movie / Series</span>
                  </a>
                </div>
              </div>
            </div>
          </div>

          {/* Parsed Body Content (Trailer, Info, Specs) */}
          {post.bodyHtml && (
            <div className="rounded-3xl bg-neutral-950/80 border border-white/10 p-6 sm:p-8 shadow-xl">
              <h3 className="text-lg font-bold text-white mb-4 pb-3 border-b border-white/10 flex items-center gap-2">
                <Film className="w-5 h-5 text-red-500" />
                <span>Movie Information & Details</span>
              </h3>

              <div
                ref={bodyRef}
                className="prose prose-invert max-w-none text-white/80 text-sm leading-relaxed space-y-4"
                dangerouslySetInnerHTML={{ __html: post.bodyHtml }}
              />
            </div>
          )}

          {/* Download Links Section */}
          {post.downloadLinks.length > 0 && (
            <div
              id="download-links-section"
              className="rounded-3xl bg-neutral-950/90 border border-red-500/30 p-6 sm:p-8 shadow-2xl space-y-4"
            >
              <div className="flex items-center justify-between pb-3 border-b border-white/10">
                <div className="flex items-center gap-2">
                  <Download className="w-5 h-5 text-red-500" />
                  <h3 className="text-lg font-bold text-white">
                    Direct Download Links
                  </h3>
                </div>
                <span className="text-xs text-white/50">
                  {post.downloadLinks.length} options
                </span>
              </div>

              <p className="text-xs text-white/60">
                Click on any download button below. Our fast resolver will provide instant direct cloud server links (HubCloud, GDFlix, Fast-DL).
              </p>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2">
                {post.downloadLinks.map((item, idx) => (
                  <button
                    key={idx}
                    id={`post-download-item-${idx}`}
                    onClick={() => handleDownloadClick(item.url, item.label)}
                    className="group flex items-center justify-between p-4 rounded-2xl bg-white/[0.03] hover:bg-red-600/10 border border-white/10 hover:border-red-500/50 transition-all text-left shadow-sm hover:shadow-[0_0_15px_rgba(220,38,38,0.25)] cursor-pointer"
                  >
                    <div className="flex items-center gap-3 min-w-0 pr-2">
                      <div className="w-10 h-10 rounded-xl bg-red-600/20 text-red-400 group-hover:bg-red-600 group-hover:text-white flex items-center justify-center border border-red-500/30 transition-colors shrink-0">
                        <Download className="w-5 h-5" />
                      </div>
                      <div className="min-w-0">
                        <p className="text-xs sm:text-sm font-bold text-white group-hover:text-red-400 transition-colors line-clamp-1">
                          {item.label}
                        </p>
                        <span className="text-[10px] text-white/40 uppercase font-mono">
                          Fast Cloud Download
                        </span>
                      </div>
                    </div>

                    <div className="px-3 py-1.5 rounded-xl bg-red-600 text-white text-xs font-semibold shrink-0 group-hover:bg-red-500 transition-colors flex items-center gap-1">
                      <span>Get Link</span>
                      <ExternalLink className="w-3 h-3" />
                    </div>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Screenshots Gallery */}
          {post.screenshots.length > 0 && (
            <div className="rounded-3xl bg-neutral-950/80 border border-white/10 p-6 sm:p-8 shadow-xl space-y-4">
              <div className="flex items-center gap-2 pb-3 border-b border-white/10">
                <ImageIcon className="w-5 h-5 text-red-500" />
                <h3 className="text-lg font-bold text-white">Screenshots</h3>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                {post.screenshots.map((src, idx) => (
                  <div
                    key={idx}
                    onClick={() => setLightboxImage(src)}
                    className="relative rounded-2xl overflow-hidden aspect-video bg-neutral-900 border border-white/10 hover:border-red-500/40 cursor-pointer transition-all group"
                  >
                    <img
                      src={src}
                      alt={`Screenshot ${idx + 1}`}
                      loading="lazy"
                      className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                    />
                    <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                      <span className="px-3 py-1 rounded-full text-xs font-semibold bg-black/70 text-white border border-white/20">
                        View Fullscreen
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {/* Download Popup Modal */}
      {activeDownloadUrl && (
        <DownloadModal
          isOpen={Boolean(activeDownloadUrl)}
          onClose={() => setActiveDownloadUrl(null)}
          title={title}
          initialUrl={activeDownloadUrl}
          label={activeDownloadLabel}
        />
      )}

      {/* Lightbox for screenshots */}
      {lightboxImage && (
        <div
          onClick={() => setLightboxImage(null)}
          className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/90 backdrop-blur-md animate-in fade-in"
        >
          <img
            src={lightboxImage}
            alt="Screenshot Fullscreen"
            className="max-w-full max-h-[90vh] object-contain rounded-2xl border border-white/20 shadow-2xl"
          />
        </div>
      )}
    </div>
  );
}
