"use client";

import React, { use, useState, useEffect } from "react";
import Link from "next/link";
import { notFound, useRouter } from "next/navigation";
import { getBlogBySlug, getBlogs, BlogPost, extractYouTubeId } from "@/services/blogService";
import VideoPlayerModal from "@/components/VideoPlayerModal";
import {
  ArrowLeft,
  Clock,
  Calendar,
  Eye,
  Share2,
  Sparkles,
  ArrowRight,
  Play,
  Film,
  Tag,
  CheckCircle2
} from "lucide-react";

export default function ArticleDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const resolvedParams = use(params);
  const router = useRouter();

  const [post, setPost] = useState<BlogPost | null>(null);
  const [relatedPosts, setRelatedPosts] = useState<BlogPost[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [copied, setCopied] = useState(false);

  // Modal Player State for related videos
  const [activeModalVideo, setActiveModalVideo] = useState<BlogPost | null>(null);
  const [isVideoModalOpen, setIsVideoModalOpen] = useState(false);

  useEffect(() => {
    let isMounted = true;
    setIsLoading(true);

    getBlogBySlug(resolvedParams.slug).then((blogData) => {
      if (isMounted) {
        if (blogData) {
          setPost(blogData);
          // Fetch related videos
          getBlogs({ category: blogData.category?.slug, per_page: 3 }).then((others) => {
            if (isMounted) {
              setRelatedPosts(others.filter((p) => String(p.id) !== String(blogData.id)).slice(0, 3));
            }
          });
        } else {
          setPost(null);
        }
        setIsLoading(false);
      }
    }).catch((err) => {
      console.warn("Failed to load property video:", err);
      if (isMounted) {
        setPost(null);
        setIsLoading(false);
      }
    });

    return () => {
      isMounted = false;
    };
  }, [resolvedParams.slug]);

  const handleShare = () => {
    if (typeof window !== "undefined") {
      navigator.clipboard.writeText(window.location.href);
      setCopied(true);
      setTimeout(() => setCopied(false), 3000);
    }
  };

  if (isLoading) {
    return (
      <div className="min-h-screen py-12 max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 space-y-6 animate-pulse">
        <div className="h-4 bg-slate-200 rounded w-32" />
        <div className="h-10 bg-slate-200 rounded w-3/4" />
        <div className="aspect-[16/9] bg-slate-200 rounded-3xl w-full" />
        <div className="space-y-3 pt-6">
          <div className="h-4 bg-slate-100 rounded w-full" />
          <div className="h-4 bg-slate-100 rounded w-5/6" />
        </div>
      </div>
    );
  }

  if (!post) {
    return (
      <div className="min-h-[70vh] flex flex-col items-center justify-center text-center px-4 py-16">
        <div className="w-16 h-16 rounded-2xl bg-rose-50 text-rose-500 flex items-center justify-center mx-auto mb-4 text-2xl font-bold">
          !
        </div>
        <h2 className="text-2xl font-extrabold text-slate-900 font-display-lg mb-2">
          Video Tour Not Found
        </h2>
        <p className="text-slate-500 text-sm max-w-md mb-6">
          The requested video walkthrough may have been unpublished or removed.
        </p>
        <Link
          href="/insights"
          className="inline-flex items-center gap-2 bg-[#4223de] text-white text-xs font-bold px-6 py-3 rounded-full hover:bg-[#381ac2] transition-colors"
        >
          <ArrowLeft className="w-4 h-4" />
          <span>Back to Video Tours</span>
        </Link>
      </div>
    );
  }

  const ytId = post.youtube_id || extractYouTubeId(post.youtube_url) || "0m_kO8c4VzI";

  return (
    <div className="min-h-screen py-10 max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 space-y-8">

      {/* Top Navigation Bar */}
      <div className="flex items-center justify-between gap-4">
        <Link
          href="/insights"
          className="inline-flex items-center gap-2 text-xs font-bold text-slate-600 hover:text-[#4223de] transition-colors"
        >
          <ArrowLeft className="w-4 h-4" />
          <span>All Video Tours &amp; Insights</span>
        </Link>

        <span className="px-3.5 py-1 rounded-full text-xs font-extrabold bg-[#deddfc] text-[#4223de]">
          {post.category?.name || post.category_name}
        </span>
      </div>

      {/* Headline & Metadata */}
      <div className="space-y-4">
        <h1 className="text-3xl sm:text-4xl md:text-5xl font-extrabold text-slate-900 tracking-tight font-display-lg leading-[1.15]">
          {post.title}
        </h1>

        <div className="flex flex-wrap items-center justify-between gap-4 pt-2 border-y border-slate-100 py-3 text-xs text-slate-500">
          <div className="flex items-center gap-3">
            <img
              src={post.author?.avatar}
              alt={post.author?.name}
              className="w-10 h-10 rounded-full object-cover border-2 border-[#4223de]"
              onError={(e) => {
                (e.currentTarget as HTMLImageElement).src = "https://images.unsplash.com/photo-1560250097-0b93528c311a?auto=format&fit=crop&w=256&q=80";
              }}
            />
            <div>
              <strong className="text-slate-900 block font-bold text-sm">{post.author?.name}</strong>
              <span className="text-slate-500 text-xs">{post.author_role}</span>
            </div>
          </div>

          <div className="flex items-center gap-4 text-xs font-medium">
            <span className="flex items-center gap-1.5">
              <Calendar className="w-3.5 h-3.5 text-slate-400" />
              <span>{post.publishedDate}</span>
            </span>
            {post.duration && (
              <span className="flex items-center gap-1.5 font-mono text-slate-700 bg-slate-100 px-2.5 py-1 rounded-full">
                <Clock className="w-3.5 h-3.5 text-[#4223de]" />
                <span>{post.duration}</span>
              </span>
            )}
            {post.view_count !== undefined && post.view_count > 0 && (
              <span className="flex items-center gap-1.5 text-slate-600 bg-slate-100 px-2.5 py-1 rounded-full">
                <Eye className="w-3.5 h-3.5 text-[#4223de]" />
                <span>{post.view_count.toLocaleString()} Views</span>
              </span>
            )}
            <button
              onClick={handleShare}
              className="inline-flex items-center gap-1.5 text-slate-600 hover:text-[#4223de] font-bold transition-colors cursor-pointer"
            >
              <Share2 className="w-3.5 h-3.5" />
              <span>{copied ? "Link Copied!" : "Share"}</span>
            </button>
          </div>
        </div>
      </div>

      {/* ------------------------------------------------------------- */}
      {/* 16:9 RESPONSIVE ZERO-REDIRECT EMBEDDED YOUTUBE VIDEO PLAYER */}
      {/* ------------------------------------------------------------- */}
      <div className="relative aspect-[16/9] rounded-3xl overflow-hidden shadow-2xl border border-slate-200 bg-black">
        <iframe
          src={`https://www.youtube-nocookie.com/embed/${ytId}?rel=0&modestbranding=1`}
          title={post.title}
          className="w-full h-full"
          frameBorder="0"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
          allowFullScreen
        />
      </div>

      {/* Video Excerpt Lead */}
      {post.excerpt && (
        <div className="bg-[#f5f4ff] border-l-4 border-[#4223de] p-6 rounded-r-2xl">
          <p className="text-slate-800 text-base sm:text-lg font-medium leading-relaxed italic">
            &ldquo;{post.excerpt}&rdquo;
          </p>
        </div>
      )}

      {/* Main Content Body */}
      <div className="prose prose-slate max-w-none prose-headings:font-display-lg prose-headings:font-extrabold prose-p:leading-relaxed prose-p:text-slate-700 text-base space-y-6">
        {post.content ? (
          post.content.includes("<p>") || post.content.includes("<h") ? (
            <div dangerouslySetInnerHTML={{ __html: post.content }} />
          ) : (
            post.content.split("\n\n").map((para, i) => (
              <p key={i} className="text-slate-700 leading-relaxed text-base sm:text-lg">
                {para}
              </p>
            ))
          )
        ) : (
          <p className="text-slate-600">Full video walkthrough notes and property specifications will load here.</p>
        )}
      </div>

      {/* Tags */}
      {post.tags && post.tags.length > 0 && (
        <div className="pt-6 border-t border-slate-100 flex items-center gap-2 flex-wrap">
          <span className="text-xs font-bold text-slate-400 flex items-center gap-1">
            <Tag className="w-3.5 h-3.5" /> Tags:
          </span>
          {post.tags.map((tag) => (
            <span
              key={tag.id}
              className="px-3 py-1 rounded-full bg-slate-100 text-slate-700 text-xs font-semibold"
            >
              #{tag.name}
            </span>
          ))}
        </div>
      )}

      {/* Related Video Tours */}
      {relatedPosts.length > 0 && (
        <div className="pt-12 border-t border-slate-200 space-y-6">
          <h3 className="text-2xl font-extrabold text-slate-900 font-display-lg">
            More Property Video Tours &amp; Guides
          </h3>

          <div className="grid grid-cols-1 sm:grid-cols-3 gap-6">
            {relatedPosts.map((item) => (
              <div
                key={item.id}
                className="group bg-white rounded-2xl overflow-hidden border border-slate-100 shadow-sm hover:shadow-md transition-all p-4 space-y-3 flex flex-col justify-between"
              >
                <div className="space-y-3">
                  <div 
                    className="relative aspect-[16/9] rounded-xl overflow-hidden bg-slate-900 cursor-pointer"
                    onClick={() => {
                      setActiveModalVideo(item);
                      setIsVideoModalOpen(true);
                    }}
                  >
                    <img
                      src={item.heroImage}
                      alt={item.title}
                      className="w-full h-full object-cover group-hover:scale-105 transition-transform"
                    />
                    <div className="absolute inset-0 bg-black/30 flex items-center justify-center">
                      <div className="w-8 h-8 rounded-full bg-red-600 text-white flex items-center justify-center shadow-md">
                        <Play className="w-3.5 h-3.5 fill-white ml-0.5" />
                      </div>
                    </div>
                    {item.duration && (
                      <span className="absolute bottom-1 right-1 px-1.5 py-0.2 rounded bg-black/80 text-white text-[9px] font-mono">
                        {item.duration}
                      </span>
                    )}
                  </div>

                  <Link href={`/insights/${item.slug}`}>
                    <h4 className="text-sm font-bold text-slate-900 group-hover:text-[#4223de] transition-colors leading-snug line-clamp-2">
                      {item.title}
                    </h4>
                  </Link>
                </div>

                <div className="text-[11px] text-slate-400 font-semibold flex items-center justify-between pt-2 border-t border-slate-50">
                  <button
                    type="button"
                    onClick={() => {
                      setActiveModalVideo(item);
                      setIsVideoModalOpen(true);
                    }}
                    className="text-red-600 font-bold hover:underline flex items-center gap-1 cursor-pointer"
                  >
                    <Play className="w-3 h-3 fill-red-600" />
                    <span>Watch</span>
                  </button>

                  <Link href={`/insights/${item.slug}`} className="text-[#4223de] font-bold group-hover:underline">
                    Details &rarr;
                  </Link>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Video Player Modal for Related Items */}
      <VideoPlayerModal
        post={activeModalVideo}
        isOpen={isVideoModalOpen}
        onClose={() => setIsVideoModalOpen(false)}
      />

    </div>
  );
}
