import { useLang } from "@/contexts/LanguageContext";
import { Button } from "@/components/ui/button";
import { motion } from "framer-motion";
import { Clock, ArrowLeft, ArrowRight, Tag, Search, ChevronLeft, ChevronRight } from "lucide-react";
import { useState, useMemo } from "react";
import { Link } from "wouter";
import { articles, categories, blogTags } from "@/data/blogData";
import SEOHead, { breadcrumbSchema } from "@/components/SEOHead";

const fadeUp = {
  hidden: { opacity: 0, y: 30 },
  visible: (i: number) => ({
    opacity: 1, y: 0,
    transition: { delay: i * 0.06, duration: 0.5, ease: [0, 0, 0.2, 1] as const }
  }),
};

const POSTS_PER_PAGE = 12;

export default function Blog() {
  const { t, lang } = useLang();
  const Arrow = lang === "ar" ? ArrowLeft : ArrowRight;
  const [activeCategory, setActiveCategory] = useState("الكل");
  const [activeTag, setActiveTag] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [currentPage, setCurrentPage] = useState(1);

  const filteredArticles = useMemo(() => {
    let filtered = [...articles].sort((a, b) => Date.parse(b.date) - Date.parse(a.date));
    if (activeCategory !== "الكل") {
      filtered = filtered.filter(a => a.categoryAr === activeCategory);
    }
    if (activeTag) {
      filtered = filtered.filter(a => a.tags && a.tags.includes(activeTag));
    }
    if (searchQuery.trim()) {
      const q = searchQuery.trim().toLowerCase();
      filtered = filtered.filter(a =>
        a.titleAr.toLowerCase().includes(q) ||
        a.titleEn.toLowerCase().includes(q) ||
        a.excerptAr.toLowerCase().includes(q) ||
        a.excerptEn.toLowerCase().includes(q)
      );
    }
    return filtered;
  }, [activeCategory, activeTag, searchQuery]);

  const handleTagChange = (tag: string) => {
    setActiveTag(tag === activeTag ? "" : tag);
    setCurrentPage(1);
  };

  // Top tags by article count
  const topTags = useMemo(() => {
    return blogTags
      .map(t => ({ ...t, count: articles.filter(a => a.tags && a.tags.includes(t.slug)).length }))
      .filter(t => t.count > 0)
      .sort((a, b) => b.count - a.count)
      .slice(0, 12);
  }, []);

  const totalPages = Math.ceil(filteredArticles.length / POSTS_PER_PAGE);
  const paginatedArticles = filteredArticles.slice(
    (currentPage - 1) * POSTS_PER_PAGE,
    currentPage * POSTS_PER_PAGE
  );

  const featured = filteredArticles.find(a => a.featured) ?? filteredArticles[0];

  const handleCategoryChange = (catAr: string) => {
    setActiveCategory(catAr);
    setCurrentPage(1);
  };

  const handleSearch = (val: string) => {
    setSearchQuery(val);
    setCurrentPage(1);
  };

  return (
    <div className="min-h-screen">
      <SEOHead
        title="مدونة دليلك | مقالات عن المنح والدراسة في الخارج"
        description="مقالات وأدلة شاملة عن المنح الدراسية، اختيار التخصص، كتابة رسائل الدافع، ونصائح القبول الجامعي."
        canonical="/blog"
        keywords="منح دراسية, مقالات تعليمية, دراسة في الخارج, نصائح قبول"
        schema={breadcrumbSchema([
          { name: "الرئيسية", url: "/" },
          { name: "المدونة", url: "/blog" },
        ])}
      />
      {/* Header */}
      <section className="bg-navy py-16 lg:py-20">
        <div className="container">
          <motion.div initial="hidden" animate="visible">
            <motion.span variants={fadeUp} custom={0} className="text-gold text-sm font-semibold uppercase tracking-wider">
              {t("المدونة", "Blog")}
            </motion.span>
            <motion.h1 variants={fadeUp} custom={1} className="text-3xl md:text-4xl lg:text-5xl font-bold text-white mt-3 mb-4 font-heading">
              {t("أدلة ونصائح للطلاب", "Guides & Tips for Students")}
            </motion.h1>
            <motion.p variants={fadeUp} custom={2} className="text-white/60 text-lg max-w-2xl">
              {t(
                `${articles.length} مقال متخصص يساعدك في رحلتك الأكاديمية من اختيار التخصص إلى الحصول على المنحة`,
                `${articles.length} specialized articles to help you on your academic journey from choosing a major to securing a scholarship.`
              )}
            </motion.p>
          </motion.div>

          {/* Search Bar */}
          <motion.div variants={fadeUp} custom={3} initial="hidden" animate="visible" className="mt-8 max-w-xl">
            <div className="relative">
              <Search className="absolute start-4 top-1/2 -translate-y-1/2 w-5 h-5 text-white/40" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => handleSearch(e.target.value)}
                placeholder={t("ابحث في المقالات...", "Search articles...")}
                className="w-full ps-12 pe-4 py-3.5 bg-white/10 border border-white/20 rounded-xl text-white placeholder:text-white/40 focus:outline-none focus:ring-2 focus:ring-gold/50 focus:border-gold/50 transition-all"
              />
            </div>
          </motion.div>
        </div>
      </section>

      {/* Categories */}
      <section className="bg-cream border-b border-border/50 sticky top-16 lg:top-18 z-30">
        <div className="container py-4">
          <div className="flex gap-2 overflow-x-auto scrollbar-hide pb-1">
            {categories.map((cat) => (
              <button
                key={cat.ar}
                onClick={() => handleCategoryChange(cat.ar)}
                className={`whitespace-nowrap px-4 py-2 rounded-full text-sm font-medium transition-all ${
                  activeCategory === cat.ar
                    ? "bg-navy text-white shadow-sm"
                    : "bg-white text-navy/70 hover:bg-navy/5 border border-border/50"
                }`}
              >
                {lang === "ar" ? cat.ar : cat.en}
              </button>
            ))}
          </div>
          {/* Tags Filter */}
          <div className="flex gap-1.5 overflow-x-auto scrollbar-hide pt-3 pb-1">
            <Tag className="w-3.5 h-3.5 text-gold mt-1.5 shrink-0" />
            {topTags.map((tag) => (
              <button
                key={tag.slug}
                onClick={() => handleTagChange(tag.slug)}
                className={`whitespace-nowrap px-3 py-1 rounded-full text-xs transition-all ${
                  activeTag === tag.slug
                    ? "bg-gold text-white"
                    : "bg-gold/5 text-navy/60 hover:bg-gold/10 hover:text-gold"
                }`}
              >
                {lang === "ar" ? tag.ar : tag.en}
              </button>
            ))}
            <Link href="/blog/tags/scholarships" className="whitespace-nowrap px-3 py-1 rounded-full text-xs bg-transparent text-gold hover:underline">
              {t("كل الوسوم", "All Tags")} →
            </Link>
          </div>
        </div>
      </section>

      {/* Featured Post - only show on first page with no filters */}
      {featured && activeCategory === "الكل" && !searchQuery && currentPage === 1 && (
        <section className="py-12 lg:py-16 bg-cream">
          <div className="container">
            <motion.div
              initial="hidden"
              whileInView="visible"
              viewport={{ once: true }}
              variants={fadeUp}
              custom={0}
            >
              <Link href={`/blog/${featured.slug}`}>
                <div className="bg-white rounded-2xl overflow-hidden shadow-sm border border-border/50 grid grid-cols-1 lg:grid-cols-2 hover:shadow-lg transition-shadow duration-300 cursor-pointer">
                  <div className="aspect-video lg:aspect-auto">
                    <img src={featured.image} alt={lang === "ar" ? featured.titleAr : featured.titleEn} className="w-full h-full object-cover" loading="lazy" />
                  </div>
                  <div className="p-8 lg:p-12 flex flex-col justify-center">
                    <div className="flex items-center gap-3 mb-4">
                      <span className="inline-flex items-center px-3 py-1 rounded-full bg-gold/10 text-navy text-xs font-medium">
                        <Tag className="w-3 h-3 me-1" />
                        {lang === "ar" ? featured.categoryAr : featured.categoryEn}
                      </span>
                      <span className="text-muted-foreground text-xs">{featured.date}</span>
                      <span className="inline-flex items-center px-2 py-0.5 rounded-full bg-navy text-white text-xs font-medium">
                        {t("مميز", "Featured")}
                      </span>
                    </div>
                    <h2 className="text-2xl lg:text-3xl font-bold text-navy mb-4 leading-tight font-heading">
                      {lang === "ar" ? featured.titleAr : featured.titleEn}
                    </h2>
                    <p className="text-muted-foreground leading-relaxed mb-6">
                      {lang === "ar" ? featured.excerptAr : featured.excerptEn}
                    </p>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2 text-muted-foreground text-sm">
                        <Clock className="w-4 h-4" />
                        {t(`${featured.readTime} دقائق قراءة`, `${featured.readTime} min read`)}
                      </div>
                      <span className="inline-flex items-center text-gold font-medium text-sm">
                        {t("اقرأ المقال", "Read Article")}
                        <Arrow className="w-4 h-4 ms-2" />
                      </span>
                    </div>
                  </div>
                </div>
              </Link>
            </motion.div>
          </div>
        </section>
      )}

      {/* Posts Grid */}
      <section className="py-12 lg:py-16 bg-cream">
        <div className="container">
          <div className="flex items-center justify-between mb-8">
            <h3 className="text-xl font-bold text-navy font-heading">
              {searchQuery
                ? t(`نتائج البحث (${filteredArticles.length})`, `Search Results (${filteredArticles.length})`)
                : activeCategory !== "الكل"
                  ? t(`${activeCategory} (${filteredArticles.length})`, `${categories.find(c => c.ar === activeCategory)?.en} (${filteredArticles.length})`)
                  : t("جميع المقالات", "All Articles")
              }
            </h3>
          </div>

          {paginatedArticles.length === 0 ? (
            <div className="text-center py-20">
              <Search className="w-12 h-12 text-muted-foreground/30 mx-auto mb-4" />
              <p className="text-muted-foreground text-lg">
                {t("لا توجد مقالات مطابقة لبحثك", "No articles match your search")}
              </p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {paginatedArticles.map((post, i) => (
                <motion.div
                  key={post.id}
                  initial="hidden"
                  whileInView="visible"
                  viewport={{ once: true }}
                  variants={fadeUp}
                  custom={i}
                >
                  <Link href={`/blog/${post.slug}`}>
                    <div className="bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 border border-border/50 group h-full flex flex-col cursor-pointer">
                      <div className="aspect-video overflow-hidden">
                        <img
                          src={post.image}
                          alt={lang === "ar" ? post.titleAr : post.titleEn}
                          className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                          loading="lazy"
                        />
                      </div>
                      <div className="p-6 flex-1 flex flex-col">
                        <div className="flex items-center gap-3 mb-3">
                          <span className="inline-flex items-center px-2.5 py-0.5 rounded-full bg-gold/10 text-navy text-xs font-medium">
                            {lang === "ar" ? post.categoryAr : post.categoryEn}
                          </span>
                          <span className="text-muted-foreground text-xs">{post.date}</span>
                        </div>
                        <h4 className="text-base font-bold text-navy mb-2 group-hover:text-gold transition-colors leading-snug line-clamp-2">
                          {lang === "ar" ? post.titleAr : post.titleEn}
                        </h4>
                        <p className="text-muted-foreground text-sm leading-relaxed flex-1 mb-4 line-clamp-3">
                          {lang === "ar" ? post.excerptAr : post.excerptEn}
                        </p>
                        <div className="flex items-center justify-between pt-4 border-t border-border/50">
                          <div className="flex items-center gap-1.5 text-muted-foreground text-xs">
                            <Clock className="w-3.5 h-3.5" />
                            {t(`${post.readTime} دقائق`, `${post.readTime} min`)}
                          </div>
                          <span className="text-gold hover:text-navy text-xs font-medium inline-flex items-center">
                            {t("اقرأ المزيد", "Read More")}
                            <Arrow className="w-3.5 h-3.5 ms-1" />
                          </span>
                        </div>
                      </div>
                    </div>
                  </Link>
                </motion.div>
              ))}
            </div>
          )}

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-center gap-2 mt-12">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                disabled={currentPage === 1}
                className="border-border/50"
              >
                {lang === "ar" ? <ChevronRight className="w-4 h-4" /> : <ChevronLeft className="w-4 h-4" />}
              </Button>
              {Array.from({ length: totalPages }, (_, i) => i + 1).map(page => (
                <Button
                  key={page}
                  variant={page === currentPage ? "default" : "outline"}
                  size="sm"
                  onClick={() => setCurrentPage(page)}
                  className={page === currentPage ? "bg-navy hover:bg-navy-light text-white" : "border-border/50"}
                >
                  {page}
                </Button>
              ))}
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                disabled={currentPage === totalPages}
                className="border-border/50"
              >
                {lang === "ar" ? <ChevronLeft className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
              </Button>
            </div>
          )}
        </div>
      </section>
    </div>
  );
}
