import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { 
  BookOpen, 
  Search, 
  Calendar, 
  Clock, 
  ArrowLeft, 
  ChevronLeft, 
  ChevronRight,
  Bot,
  Cpu,
  Wand2,
  TrendingUp,
  HelpCircle,
  Image as ImageIcon
} from 'lucide-react';
import postsData from '../data/posts.json';

export const getCategoryCover = (category: string) => {
  if (category.includes('معرفی ابزار') || category.includes('راهنمای')) {
    return {
      gradient: 'from-cyan-950 via-slate-900 to-indigo-950',
      icon: Wand2,
      badgeColor: 'bg-cyan-500/20 text-cyan-300'
    };
  }
  if (category.includes('آموزش') || category.includes('پرامپت')) {
    return {
      gradient: 'from-indigo-950 via-slate-900 to-purple-950',
      icon: Cpu,
      badgeColor: 'bg-indigo-500/20 text-indigo-300'
    };
  }
  if (category.includes('داستان') || category.includes('کسب')) {
    return {
      gradient: 'from-emerald-950 via-slate-900 to-slate-950',
      icon: TrendingUp,
      badgeColor: 'bg-emerald-500/20 text-emerald-300'
    };
  }
  if (category.includes('سوالات') || category.includes('رایج')) {
    return {
      gradient: 'from-amber-950 via-slate-900 to-slate-950',
      icon: HelpCircle,
      badgeColor: 'bg-amber-500/20 text-amber-300'
    };
  }
  return {
    gradient: 'from-purple-950 via-slate-900 to-slate-950',
    icon: Bot,
    badgeColor: 'bg-purple-500/20 text-purple-300'
  };
};

export const Blog: React.FC = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [currentPage, setCurrentPage] = useState(1);
  const [imgErrors, setImgErrors] = useState<Record<number, boolean>>({});
  const postsPerPage = 9;

  const categories = [
    'all',
    'معرفی ابزارهای هوش مصنوعی',
    'اخبار و تحولات دنیای هوش مصنوعی',
    'آموزش هوش مصنوعی',
    'داستان موفقیت هوش مصنوعی',
    'سوالات رایج هوش مصنوعی',
    'راهنمای استفاده از ابزار'
  ];

  const filteredPosts = postsData.filter((post) => {
    const matchesCat = selectedCategory === 'all' || post.categories.includes(selectedCategory);
    const matchesSearch = post.title.toLowerCase().includes(searchQuery.toLowerCase()) || 
                          post.excerpt.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          post.content.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesCat && matchesSearch;
  });

  const totalPages = Math.ceil(filteredPosts.length / postsPerPage);
  const currentPosts = filteredPosts.slice(
    (currentPage - 1) * postsPerPage,
    currentPage * postsPerPage
  );

  return (
    <div className="pt-28 pb-20 bg-slate-950 min-h-screen">
      {/* Background Glow */}
      <div className="absolute top-20 right-1/4 w-[600px] h-[350px] bg-indigo-600/10 rounded-full blur-3xl pointer-events-none" />

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
        
        {/* Page Header */}
        <div className="text-center max-w-3xl mx-auto space-y-4 mb-14">
          <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-indigo-500/10 border border-indigo-500/20 text-indigo-400 text-xs font-semibold">
            <BookOpen className="w-3.5 h-3.5" />
            <span>رسانه هوش مصنوعی هوشان ({postsData.length} مقاله تخصصی)</span>
          </div>
          <h1 className="text-3xl sm:text-5xl font-black text-white tracking-tight">
            مرجع مقالات، اخبار و آموزش‌های هوش مصنوعی
          </h1>
          <p className="text-sm text-slate-300 leading-relaxed font-light">
            به‌روزترین مقالات تحلیلی، راهنماهای مهندسی پرامپت، بررسی ابزارها و داستان‌های موفقیت پیاده‌سازی هوش مصنوعی در کسب‌وکارها.
          </p>
        </div>

        {/* Filters and Search Bar */}
        <div className="flex flex-col md:flex-row items-center justify-between gap-4 mb-10">
          <div className="flex items-center gap-2 overflow-x-auto w-full md:w-auto pb-2">
            {categories.map((cat) => (
              <button
                key={cat}
                onClick={() => {
                  setSelectedCategory(cat);
                  setCurrentPage(1);
                }}
                className={`px-3.5 py-2 rounded-xl text-xs font-semibold transition-all shrink-0 cursor-pointer ${
                  selectedCategory === cat
                    ? 'bg-indigo-600 text-white shadow-md shadow-indigo-600/25'
                    : 'bg-slate-900 text-slate-400 hover:text-slate-200 border border-slate-800'
                }`}
              >
                {cat === 'all' ? `همه مقالات (${postsData.length})` : cat}
              </button>
            ))}
          </div>

          <div className="w-full md:w-72 relative">
            <input
              type="text"
              placeholder="جستجو در بین مقالات..."
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                setCurrentPage(1);
              }}
              className="w-full pl-4 pr-10 py-2.5 rounded-xl bg-slate-900 border border-slate-800 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500"
            />
            <Search className="w-4 h-4 text-slate-500 absolute right-3.5 top-3" />
          </div>
        </div>

        {/* Articles Grid */}
        {currentPosts.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-12">
            {currentPosts.map((post) => {
              const theme = getCategoryCover(post.categories[0] || '');
              const Icon = theme.icon;
              const hasImg = post.thumbnail && !imgErrors[post.id];

              return (
                <article 
                  key={post.id}
                  className="rounded-3xl bg-slate-900/50 border border-slate-800/80 hover:border-indigo-500/40 glass-panel-hover flex flex-col justify-between overflow-hidden group"
                >
                  <div>
                    {/* Cover Section */}
                    <div className="relative h-48 w-full bg-slate-950 overflow-hidden border-b border-slate-800/80">
                      {hasImg ? (
                        <>
                          <img 
                            src={post.thumbnail} 
                            alt={post.title} 
                            className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                            onError={() => setImgErrors(prev => ({ ...prev, [post.id]: true }))}
                          />
                          <div className="absolute inset-0 bg-gradient-to-t from-slate-950 via-slate-950/20 to-transparent pointer-events-none" />
                        </>
                      ) : (
                        <div className={`w-full h-full bg-gradient-to-br ${theme.gradient} flex flex-col justify-between p-5`}>
                          <div className="flex items-center justify-between z-10">
                            <span className={`text-[10px] font-bold px-2.5 py-1 rounded-full ${theme.badgeColor} backdrop-blur-md`}>
                              {post.categories[0] || 'هوش مصنوعی'}
                            </span>
                            <div className="w-8 h-8 rounded-xl bg-slate-950/60 border border-slate-800 flex items-center justify-center text-slate-300">
                              <Icon className="w-4 h-4" />
                            </div>
                          </div>
                          <div className="z-10 text-right">
                            <span className="text-[10px] font-bold text-slate-400 font-mono block">#HOUSHAN_AI</span>
                            <h4 className="text-xs font-bold text-white line-clamp-1 mt-0.5">{post.title}</h4>
                          </div>
                        </div>
                      )}

                      {/* Floating Category Badge if image exists */}
                      {hasImg && (
                        <div className="absolute top-3 right-3 z-10">
                          <span className="text-[10px] font-bold px-2.5 py-1 rounded-full bg-indigo-600/90 text-white backdrop-blur-md shadow-md">
                            {post.categories[0] || 'هوش مصنوعی'}
                          </span>
                        </div>
                      )}
                    </div>

                    {/* Body */}
                    <div className="p-6 space-y-3">
                      <div className="flex items-center gap-4 text-[11px] text-slate-400">
                        <span className="flex items-center gap-1">
                          <Calendar className="w-3.5 h-3.5 text-slate-500" />
                          {post.date}
                        </span>
                        <span className="flex items-center gap-1">
                          <Clock className="w-3.5 h-3.5 text-slate-500" />
                          {post.readTime}
                        </span>
                      </div>

                      <h3 className="text-base font-bold text-white group-hover:text-indigo-300 transition-colors line-clamp-2">
                        <Link to={`/blog/${post.slug}`}>
                          {post.title}
                        </Link>
                      </h3>

                      <p className="text-xs text-slate-400 leading-relaxed line-clamp-3">
                        {post.excerpt}
                      </p>
                    </div>
                  </div>

                  {/* Footer Action */}
                  <div className="px-6 pb-6 pt-2">
                    <Link
                      to={`/blog/${post.slug}`}
                      className="inline-flex items-center gap-2 text-xs font-bold text-indigo-400 hover:text-indigo-300 transition-colors"
                    >
                      <span>مطالعه کامل مقاله</span>
                      <ArrowLeft className="w-3.5 h-3.5" />
                    </Link>
                  </div>
                </article>
              );
            })}
          </div>
        ) : (
          <div className="text-center py-16 text-slate-400 space-y-3">
            <BookOpen className="w-12 h-12 text-slate-600 mx-auto" />
            <h3 className="text-base font-bold text-white">مقاله‌ای با این مشخصات یافت نشد</h3>
            <p className="text-xs">لطفاً عبارت دیگری را جستجو کنید یا فیلتر دسته‌بندی را تغییر دهید.</p>
          </div>
        )}

        {/* Pagination Controls */}
        {totalPages > 1 && (
          <div className="flex items-center justify-center gap-2 pt-6">
            <button
              onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
              disabled={currentPage === 1}
              className="p-2.5 rounded-xl bg-slate-900 border border-slate-800 text-slate-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed cursor-pointer"
            >
              <ChevronRight className="w-4 h-4" />
            </button>

            {Array.from({ length: Math.min(6, totalPages) }, (_, i) => {
              const pageNum = i + 1;
              return (
                <button
                  key={pageNum}
                  onClick={() => setCurrentPage(pageNum)}
                  className={`w-9 h-9 rounded-xl text-xs font-bold transition-all cursor-pointer ${
                    currentPage === pageNum
                      ? 'bg-indigo-600 text-white shadow-md shadow-indigo-600/30'
                      : 'bg-slate-900 text-slate-400 hover:text-slate-200 border border-slate-800'
                  }`}
                >
                  {pageNum}
                </button>
              );
            })}

            <button
              onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
              disabled={currentPage === totalPages}
              className="p-2.5 rounded-xl bg-slate-900 border border-slate-800 text-slate-400 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed cursor-pointer"
            >
              <ChevronLeft className="w-4 h-4" />
            </button>
          </div>
        )}

      </div>
    </div>
  );
};
