"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { getBlogs, getBlogCategories, BlogPost } from "@/services/blogService";
import VideoPlayerModal from "@/components/VideoPlayerModal";
import {
  Play,
  Clock,
  Sparkles,
  Search,
  Eye,
  ArrowRight,
  Film,
  Video,
  Layers,
  MapPin,
  CheckCircle2
} from "lucide-react";

export default function MarketInsightsPage() {
  const [articles, setArticles] = useState<BlogPost[]>([]);
  const [categories, setCategories] = useState<string[]>([
    "All",
    "Property Tours",
    "Market Trends",
    "Architecture",
    "Legal & Tax",
    "Construction Guide"
  ]);
  const [selectedCategory, setSelectedCategory] = useState("All");
  const [searchQuery, setSearchQuery] = useState("");
  const [isLoading, setIsLoading] = useState(true);

  // Video Modal State
  const [activeModalVideo, setActiveModalVideo] = useState<BlogPost | null>(null);
  const [isVideoModalOpen, setIsVideoModalOpen] = useState(false);

  const handlePlayVideo = (post: BlogPost) => {
    setActiveModalVideo(post);
    setIsVideoModalOpen(true);
  };

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

    Promise.all([
      getBlogs(),
      getBlogCategories()
    ]).then(([blogsData, categoriesData]) => {
      if (isMounted) {
        setArticles(blogsData || []);
        if (categoriesData && categoriesData.length > 0) {
          const names = categoriesData.map((c) => c.name);
          setCategories(["All", ...Array.from(new Set(["Property Tours", ...names]))]);
        }
        setIsLoading(false);
      }
    }).catch((err) => {
      console.warn("Failed to load property videos from backend:", err);
      if (isMounted) {
        setArticles([]);
        setIsLoading(false);
      }
    });

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

  const filteredArticles = articles.filter((art) => {
    const artCat = art.category?.name || art.category_name || "";
    if (selectedCategory !== "All" && artCat.toLowerCase() !== selectedCategory.toLowerCase()) {
      return false;
    }
    if (searchQuery) {
      const q = searchQuery.toLowerCase();
      const matchTitle = art.title.toLowerCase().includes(q);
      const matchExcerpt = (art.excerpt || "").toLowerCase().includes(q);
      const matchCategory = artCat.toLowerCase().includes(q);
      if (!matchTitle && !matchExcerpt && !matchCategory) return false;
    }
    return true;
  });

  const featuredArticle = articles.find((a) => a.is_featured || a.featured) || articles[0];

  return (
    <div className="min-h-screen py-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-12">

      {/* Header */}
      <div className="mb-12 text-center max-w-3xl mx-auto space-y-4">
        <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#0A0A0A] text-xs font-extrabold text-[#FFE259] border border-[#FFA726]/40 shadow-sm">
          <Film className="w-3.5 h-3.5 text-[#FFE259]" />
          <span>Real Estate Video Tours &amp; Market Intelligence</span>
        </div>
        <h1 className="text-3xl sm:text-4xl md:text-5xl font-extrabold text-white tracking-tight font-display-lg">
          Sri Lanka Real Estate <span className="text-[#FFE259]">Insights &amp; Video Tours</span>
        </h1>
        <p className="text-slate-400 text-sm sm:text-base leading-relaxed">
          Authoritative analysis on land valuation benchmarks, foreign ownership regulations, construction cost dynamics, and luxury property video tours.
        </p>
      </div>

      {/* Loading Skeleton */}
      {isLoading ? (
        <div className="space-y-8">
          <div className="bg-[#0e0e10] rounded-3xl p-8 border border-zinc-800 shadow-xl animate-pulse grid grid-cols-1 lg:grid-cols-12 gap-8">
            <div className="lg:col-span-7 aspect-[16/9] bg-zinc-800 rounded-3xl w-full" />
            <div className="lg:col-span-5 space-y-4 py-4">
              <div className="h-4 bg-zinc-800 rounded w-1/4" />
              <div className="h-8 bg-zinc-800 rounded w-3/4" />
              <div className="h-16 bg-zinc-900 rounded w-full" />
              <div className="h-12 bg-zinc-800 rounded-full w-1/2 mt-6" />
            </div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            {[1, 2, 3].map((n) => (
              <div key={n} className="bg-[#0e0e10] rounded-3xl p-6 border border-zinc-800 shadow-xl animate-pulse space-y-4">
                <div className="aspect-[16/9] bg-zinc-800 rounded-2xl w-full" />
                <div className="h-4 bg-zinc-800 rounded w-1/3" />
                <div className="h-6 bg-zinc-800 rounded w-3/4" />
                <div className="h-12 bg-zinc-900 rounded" />
              </div>
            ))}
          </div>
        </div>
      ) : articles.length === 0 ? (
        /* Empty State */
        <div className="bg-[#0e0e10] border border-[#FFE259]/30 rounded-3xl p-16 text-center max-w-lg mx-auto space-y-4 text-white">
          <div className="w-16 h-16 rounded-2xl bg-[#FFE259]/10 text-[#FFE259] border border-[#FFE259]/30 mx-auto flex items-center justify-center">
            <Video className="w-8 h-8" />
          </div>
          <h3 className="text-xl font-bold text-white font-display-lg">No Property Articles Published Yet</h3>
          <p className="text-xs text-slate-400 max-w-xs mx-auto">
            Articles and video property tours published in the Admin Portal will appear here automatically.
          </p>
        </div>
      ) : (
        <>
          {/* Featured Master Article Banner */}
          {!searchQuery && selectedCategory === "All" && featuredArticle && (
            <div className="bg-[#0e0e10] rounded-3xl border border-[#FFE259]/30 text-white overflow-hidden shadow-2xl mb-12 grid grid-cols-1 lg:grid-cols-12">
              <div 
                className="lg:col-span-6 relative aspect-[16/10] lg:aspect-auto min-h-[300px] overflow-hidden group cursor-pointer"
                onClick={() => handlePlayVideo(featuredArticle)}
              >
                <img
                  src={featuredArticle.heroImage || "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=1200&q=80"}
                  alt={featuredArticle.title}
                  className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-700 opacity-90 group-hover:opacity-100"
                  onError={(e) => {
                    (e.currentTarget as HTMLImageElement).src = "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=1200&q=80";
                  }}
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/30 to-transparent" />
                <div className="absolute top-4 left-4">
                  <span className="px-3.5 py-1.5 rounded-full text-xs font-extrabold bg-[#FFE259] text-black shadow-md border border-[#FFE259] flex items-center gap-1.5">
                    <Sparkles className="w-3.5 h-3.5" />
                    <span>Featured Intelligence Report</span>
                  </span>
                </div>

                {/* Animated Center Play Button if Video */}
                {featuredArticle.youtube_url && (
                  <div className="absolute inset-0 flex items-center justify-center">
                    <div className="relative">
                      <div className="absolute -inset-3 rounded-full bg-red-600/40 animate-ping" />
                      <div className="w-16 h-16 rounded-full bg-red-600 group-hover:bg-red-700 text-white flex items-center justify-center shadow-2xl transition-transform group-hover:scale-110">
                        <Play className="w-7 h-7 fill-white ml-1" />
                      </div>
                    </div>
                  </div>
                )}
              </div>

              <div className="lg:col-span-6 p-8 sm:p-12 flex flex-col justify-between space-y-6">
                <div className="space-y-3">
                  <div className="flex items-center gap-3 text-xs font-bold text-slate-400 flex-wrap">
                    <span className="text-[#FFE259] font-extrabold">{featuredArticle.category?.name || featuredArticle.category_name || "Insights"}</span>
                    <span>•</span>
                    <span className="flex items-center gap-1">
                      <Clock className="w-3.5 h-3.5 text-[#FFE259]" /> {featuredArticle.duration || featuredArticle.readTime || "5 min read"}
                    </span>
                    <span>•</span>
                    <span>{featuredArticle.publishedDate}</span>
                  </div>

                  <h2 
                    onClick={() => handlePlayVideo(featuredArticle)}
                    className="text-2xl sm:text-3xl font-extrabold text-white tracking-tight font-display-lg hover:text-[#FFE259] transition-colors cursor-pointer"
                  >
                    {featuredArticle.title}
                  </h2>

                  <p className="text-slate-300 text-xs sm:text-sm leading-relaxed line-clamp-3">
                    {featuredArticle.excerpt || featuredArticle.summary || ""}
                  </p>
                </div>

                <div className="pt-4 border-t border-zinc-800 flex items-center justify-between gap-3 flex-wrap">
                  <div className="text-xs">
                    <strong className="text-white block font-bold">{featuredArticle.author?.name || featuredArticle.author_name || "DreamHomes Research"}</strong>
                    <span className="text-slate-400">{featuredArticle.author_role || "Research Team"}</span>
                  </div>

                  <div className="flex items-center gap-2.5">
                    {featuredArticle.youtube_url && (
                      <button
                        type="button"
                        onClick={() => handlePlayVideo(featuredArticle)}
                        className="bg-red-600 hover:bg-red-700 text-white text-xs font-bold px-5 py-2.5 rounded-full shadow-md transition-all flex items-center gap-1.5 cursor-pointer"
                      >
                        <Play className="w-3.5 h-3.5 fill-white" />
                        <span>Watch Video</span>
                      </button>
                    )}
                    <Link
                      href={featuredArticle.slug ? `/insights/${featuredArticle.slug}` : "/insights/construction-cost-guide"}
                      className="bg-[#059669] hover:bg-[#047857] text-white text-xs font-extrabold px-6 py-2.5 rounded-full shadow-md transition-all flex items-center gap-2"
                    >
                      <span>Read Guide</span>
                      <ArrowRight className="w-4 h-4" />
                    </Link>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Filter & Search Bar */}
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-10 pb-6 border-b border-zinc-700">
            <div className="flex flex-wrap gap-1.5">
              {categories.map((cat) => (
                <button
                  key={cat}
                  onClick={() => setSelectedCategory(cat)}
                  className={`px-4 py-2 rounded-full text-xs font-bold transition-all cursor-pointer ${
                    selectedCategory.toLowerCase() === cat.toLowerCase()
                      ? "bg-[#FFE259] text-black font-extrabold shadow-md border border-[#FFE259] scale-[1.02]"
                      : "bg-[#18181b] text-slate-300 border border-zinc-800 hover:text-white hover:border-[#FFE259]/50 hover:bg-[#202024]"
                  }`}
                >
                  {cat}
                </button>
              ))}
            </div>

            <div className="relative min-w-[260px]">
              <input
                type="text"
                placeholder="Search articles by title, topic..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full bg-[#18181b] border border-zinc-700 text-white placeholder-slate-400 focus:border-[#FFE259] rounded-full pl-9 pr-4 py-2 text-xs focus:outline-none transition-colors"
              />
              <Search className="w-4 h-4 text-[#FFE259] absolute left-3 top-2.5" />
            </div>
          </div>

          {/* Articles Grid */}
          {filteredArticles.length === 0 ? (
            <div className="text-center py-16 bg-[#0e0e10] rounded-3xl border border-zinc-800 p-8 space-y-2 text-white">
              <h3 className="font-bold text-white text-base">No Articles Found</h3>
              <p className="text-xs text-slate-400">Try selecting another category or clear your search keyword.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
              {filteredArticles.map((article) => (
                <div
                  key={article.id}
                  className="group bg-[#0e0e10] rounded-3xl border border-[#FFE259]/25 text-white overflow-hidden shadow-xl hover:border-[#FFE259]/60 hover:shadow-2xl transition-all flex flex-col justify-between"
                >
                  <div>
                    <div 
                      className="relative aspect-[16/10] overflow-hidden bg-[#18181b] cursor-pointer"
                      onClick={() => {
                        if (article.youtube_url) {
                          handlePlayVideo(article);
                        }
                      }}
                    >
                      <img
                        src={article.heroImage || "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=1000&q=80"}
                        alt={article.title}
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500 opacity-90 group-hover:opacity-100"
                        onError={(e) => {
                          (e.currentTarget as HTMLImageElement).src = "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=1000&q=80";
                        }}
                      />
                      <div className="absolute top-3 left-3 px-3 py-1 rounded-full text-xs font-extrabold bg-[#FFE259] text-black shadow-md border border-[#FFE259]/80">
                        {article.category?.name || article.category_name || "Insights"}
                      </div>

                      {/* Video Play Button Overlay if has video */}
                      {article.youtube_url && (
                        <div className="absolute inset-0 flex items-center justify-center bg-black/25">
                          <div className="w-11 h-11 rounded-full bg-red-600 group-hover:bg-red-700 text-white flex items-center justify-center shadow-lg transition-transform group-hover:scale-110">
                            <Play className="w-4 h-4 fill-white ml-0.5" />
                          </div>
                        </div>
                      )}
                    </div>

                    <div className="p-6 space-y-3">
                      <div className="flex items-center gap-2 text-[11px] font-semibold text-slate-400">
                        <Clock className="w-3.5 h-3.5 text-[#FFE259]" />
                        <span>{article.duration || article.readTime || "5 min read"}</span>
                        <span>•</span>
                        <span>{article.publishedDate}</span>
                      </div>

                      <h3 className="text-xl font-bold text-white group-hover:text-[#FFE259] transition-colors font-display-lg line-clamp-2">
                        {article.title}
                      </h3>

                      <p className="text-xs text-slate-300 line-clamp-3 leading-relaxed">
                        {article.excerpt || article.summary || ""}
                      </p>
                    </div>
                  </div>

                  <div className="p-6 pt-0 flex items-center justify-between border-t border-zinc-800/80 mt-4">
                    {article.youtube_url ? (
                      <button
                        type="button"
                        onClick={() => handlePlayVideo(article)}
                        className="inline-flex items-center gap-1 text-xs font-bold text-red-500 hover:text-red-400 transition-colors cursor-pointer"
                      >
                        <Play className="w-3.5 h-3.5 fill-current" />
                        <span>Watch Tour</span>
                      </button>
                    ) : (
                      <span />
                    )}

                    <Link
                      href={article.slug ? `/insights/${article.slug}` : "/insights/construction-cost-guide"}
                      className="inline-flex items-center gap-1.5 text-xs font-bold text-[#FFE259] hover:underline ml-auto"
                    >
                      <span>Read Article</span>
                      <ArrowRight className="w-3.5 h-3.5" />
                    </Link>
                  </div>
                </div>
              ))}
            </div>
          )}
        </>
      )}

      {/* Video Player Modal */}
      <VideoPlayerModal
        post={activeModalVideo}
        isOpen={isVideoModalOpen}
        onClose={() => setIsVideoModalOpen(false)}
      />

    </div>
  );
}