import React, { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { 
  Calendar, 
  Clock, 
  Share2, 
  ArrowRight, 
  Tag, 
  BookOpen, 
  Check, 
  Bot,
  Wand2,
  Cpu,
  TrendingUp,
  HelpCircle
} from 'lucide-react';
import postsData from '../data/posts.json';
import { getCategoryCover } from './Blog';

export const BlogPost: React.FC = () => {
  const { slug } = useParams<{ slug: string }>();
  const [copied, setCopied] = useState(false);
  const [scrollProgress, setScrollProgress] = useState(0);
  const [imgError, setImgError] = useState(false);

  const post = postsData.find((p) => p.slug === slug || String(p.id) === slug);

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'smooth' });

    const handleScroll = () => {
      const totalHeight = document.documentElement.scrollHeight - window.innerHeight;
      if (totalHeight > 0) {
        setScrollProgress((window.scrollY / totalHeight) * 100);
      }
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [slug]);

  if (!post) {
    return (
      <div className="pt-36 pb-20 text-center space-y-4 max-w-lg mx-auto px-4">
        <h2 className="text-xl font-bold text-white">مقاله مورد نظر یافت نشد</h2>
        <p className="text-xs text-slate-400">ممکن است این نوشته حذف یا آدرس آن تغییر کرده باشد.</p>
        <Link
          to="/blog"
          className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-indigo-600 text-white text-xs font-bold"
        >
          <span>بازگشت به وبلاگ</span>
        </Link>
      </div>
    );
  }

  const theme = getCategoryCover(post.categories[0] || '');
  const Icon = theme.icon;
  const hasImg = post.thumbnail && !imgError;

  const relatedPosts = postsData
    .filter((p) => p.id !== post.id && p.categories.some(c => post.categories.includes(c)))
    .slice(0, 3);

  const handleShare = () => {
    if (navigator.share) {
      navigator.share({
        title: post.title,
        url: window.location.href,
      }).catch(() => {});
    } else {
      navigator.clipboard.writeText(window.location.href);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  return (
    <div className="pt-28 pb-20 bg-slate-950 min-h-screen">
      {/* Scroll Progress Bar */}
      <div 
        className="fixed top-0 left-0 right-0 h-1 bg-gradient-to-r from-indigo-500 via-cyan-400 to-indigo-500 z-50 transition-all duration-100"
        style={{ width: `${scrollProgress}%` }}
      />

      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
        
        {/* Breadcrumb & Back */}
        <div className="flex items-center justify-between gap-4 mb-8 text-xs text-slate-400">
          <Link to="/blog" className="inline-flex items-center gap-1.5 hover:text-white transition-colors">
            <ArrowRight className="w-4 h-4" />
            <span>بازگشت به مقالات رسانه هوشان</span>
          </Link>
          <div className="flex items-center gap-2">
            <span className={`px-2.5 py-0.5 rounded-full ${theme.badgeColor} border border-indigo-500/20 text-[11px] font-semibold`}>
              {post.categories[0] || 'هوش مصنوعی'}
            </span>
          </div>
        </div>

        {/* Featured Cover Image if available */}
        {hasImg && (
          <div className="mb-8 rounded-3xl overflow-hidden border border-slate-800 max-h-[420px] shadow-2xl relative">
            <img 
              src={post.thumbnail} 
              alt={post.title} 
              className="w-full h-full object-cover"
              onError={() => setImgError(true)}
            />
            <div className="absolute inset-0 bg-gradient-to-t from-slate-950/80 via-transparent to-transparent" />
          </div>
        )}

        {/* Themed Banner Header */}
        <div className={`mb-8 p-8 rounded-3xl bg-gradient-to-br ${theme.gradient} border border-slate-800 shadow-2xl relative overflow-hidden flex flex-col justify-between`}>
          <div className="flex items-center justify-between z-10">
            <div className="flex items-center gap-2">
              <div className="w-10 h-10 rounded-2xl bg-slate-950/60 border border-slate-800 flex items-center justify-center text-cyan-300">
                <Icon className="w-5 h-5" />
              </div>
              <span className="text-xs font-bold text-slate-300 font-mono">HOUSHAN RESEARCH</span>
            </div>
            <button
              onClick={handleShare}
              className="px-3.5 py-1.5 rounded-xl bg-slate-950/80 hover:bg-slate-800 text-slate-300 border border-slate-800 text-xs font-semibold flex items-center gap-1.5 transition-colors cursor-pointer"
            >
              {copied ? <Check className="w-3.5 h-3.5 text-emerald-400" /> : <Share2 className="w-3.5 h-3.5" />}
              <span>{copied ? 'لینک کپی شد' : 'اشتراک‌گذاری'}</span>
            </button>
          </div>

          <div className="z-10 mt-6 space-y-3">
            <h1 className="text-2xl sm:text-4xl font-black text-white leading-snug">
              {post.title}
            </h1>

            <div className="flex flex-wrap items-center gap-4 text-xs text-slate-300 pt-2">
              <div className="flex items-center gap-1.5">
                <Calendar className="w-3.5 h-3.5 text-slate-400" />
                <span>{post.date}</span>
              </div>
              <div className="flex items-center gap-1.5">
                <Clock className="w-3.5 h-3.5 text-slate-400" />
                <span>زمان مطالعه: {post.readTime}</span>
              </div>
              <div className="flex items-center gap-1.5">
                <Bot className="w-3.5 h-3.5 text-indigo-400" />
                <span>تیم پژوهش هوشان</span>
              </div>
            </div>
          </div>
        </div>

        {/* Article Body Content */}
        <article className="p-6 sm:p-10 rounded-3xl bg-slate-900/40 border border-slate-800/80 shadow-xl space-y-6 text-sm sm:text-base text-slate-200 leading-loose">
          <div 
            className="prose prose-invert max-w-none space-y-4 font-light [&_p]:leading-loose [&_h2]:text-xl [&_h2]:font-bold [&_h2]:text-white [&_h2]:pt-4 [&_h3]:text-lg [&_h3]:font-semibold [&_h3]:text-indigo-300 [&_ul]:list-disc [&_ul]:pr-6 [&_ol]:list-decimal [&_ol]:pr-6 [&_a]:text-cyan-400 [&_a]:underline [&_img]:rounded-2xl [&_img]:mx-auto"
            dangerouslySetInnerHTML={{ __html: post.content }}
          />
        </article>

        {/* Tags */}
        {post.tags && post.tags.length > 0 && (
          <div className="mt-8 p-4 rounded-2xl bg-slate-900/60 border border-slate-800/80 flex flex-wrap items-center gap-2">
            <Tag className="w-4 h-4 text-indigo-400 shrink-0 ml-1" />
            <span className="text-xs text-slate-400 font-semibold">برچسب‌ها:</span>
            {post.tags.map((tag, idx) => (
              <span 
                key={idx}
                className="text-[11px] px-2.5 py-1 rounded-lg bg-slate-800 text-slate-300"
              >
                #{tag}
              </span>
            ))}
          </div>
        )}

        {/* Related Articles */}
        {relatedPosts.length > 0 && (
          <div className="mt-16 space-y-6">
            <h3 className="text-xl font-bold text-white flex items-center gap-2">
              <BookOpen className="w-5 h-5 text-indigo-400" />
              <span>مقالات مرتبط پیشنهادی</span>
            </h3>

            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              {relatedPosts.map((rp) => (
                <Link
                  key={rp.id}
                  to={`/blog/${rp.slug}`}
                  className="p-5 rounded-2xl bg-slate-900/50 border border-slate-800/80 hover:border-indigo-500/40 glass-panel-hover flex flex-col justify-between space-y-3 group"
                >
                  <div className="space-y-2">
                    <span className="text-[10px] text-indigo-400 font-semibold">
                      {rp.categories[0]}
                    </span>
                    <h4 className="text-xs font-bold text-white group-hover:text-indigo-300 transition-colors line-clamp-2">
                      {rp.title}
                    </h4>
                  </div>
                  <div className="text-[10px] text-slate-500 flex items-center justify-between pt-2 border-t border-slate-800/60">
                    <span>{rp.date}</span>
                    <span>{rp.readTime}</span>
                  </div>
                </Link>
              ))}
            </div>
          </div>
        )}

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