import Navigation from '@/components/Navigation';
import Footer from '@/components/Footer';
import { Calendar, Clock, ArrowLeft, Share2, ArrowUp } from 'lucide-react';
import { Link, useParams, Navigate } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react';
import { blogPosts } from '@/data/blogPosts';
import { generateArticleSchema, injectStructuredData } from '@/utils/structuredData';
import { useSEO } from '@/hooks/useSEO';
import ScrollReveal from '@/components/ScrollReveal';

const BlogPost = () => {
  const { slug } = useParams<{ slug: string }>();
  const contentRef = useRef<HTMLDivElement>(null);
  const [showScrollTop, setShowScrollTop] = useState(false);

  // Find the blog post by slug
  const post = blogPosts.find(p => p.slug === slug);

  // Redirect to 404 if post not found
  if (!post) {
    return <Navigate to="/404" replace />;
  }

  // Scroll to top when slug changes (navigating to different blog post)
  useEffect(() => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  }, [slug]);

  // SEO metadata for this specific post
  useSEO({
    title: `${post.title} | Bay Area Affiliates Blog`,
    description: post.excerpt,
    keywords: post.keywords.join(', '),
    canonical: `https://bayarea-cc.com/blog/${post.slug}`,
    ogTitle: post.title,
    ogDescription: post.excerpt,
    ogImage: post.image,
    type: 'article',
    author: post.author,
    publishedTime: post.date,
  });

  // Inject Article Schema with entity mentions
  useEffect(() => {
    const schema = generateArticleSchema({
      headline: post.title,
      description: post.excerpt,
      author: post.author,
      datePublished: post.date,
      url: `https://bayarea-cc.com/blog/${post.slug}`,
      keywords: post.keywords,
      image: post.image,
    });

    // Add entity mentions for Knowledge Graph
    const schemaWithEntities = {
      ...schema,
      mentions: post.entities,
    };

    injectStructuredData(schemaWithEntities, `blog-post-${post.id}-schema`);
  }, [post]);

  // Render HTML content safely
  useEffect(() => {
    if (contentRef.current && post.content) {
      contentRef.current.innerHTML = post.content;
    }
  }, [post.content]);

  // Scroll to top button visibility
  useEffect(() => {
    const handleScroll = () => {
      setShowScrollTop(window.scrollY > 500);
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

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

  const handleShare = async () => {
    const shareData = {
      title: post.title,
      text: post.excerpt,
      url: window.location.href,
    };

    if (navigator.share) {
      try {
        await navigator.share(shareData);
      } catch (err) {
        console.log('Error sharing:', err);
      }
    } else {
      // Fallback: Copy URL to clipboard
      navigator.clipboard.writeText(window.location.href);
      alert('Link copied to clipboard!');
    }
  };

  return (
    <div className="min-h-screen bg-background-deep">
      <Navigation />

      <main>
        {/* Hero section with featured image */}
        <section className="relative h-[60vh] min-h-[400px] flex items-center justify-center overflow-hidden">
          {/* Background image */}
          <div className="absolute inset-0">
            <img
              src={post.image}
              alt={post.title}
              className="w-full h-full object-cover"
              loading="eager"
              fetchpriority="high"
            />
            <div className="absolute inset-0 bg-gradient-to-t from-background-deep via-background-deep/60 to-transparent"></div>
          </div>

          {/* Hero content */}
          <div className="relative z-10 max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
            <ScrollReveal>
              <div className="inline-block px-3 py-1 bg-neon text-neon-foreground text-sm font-medium rounded-full mb-4">
                {post.category}
              </div>
              <h1 className="font-heading font-bold text-4xl sm:text-5xl lg:text-6xl text-white mb-6 text-balance drop-shadow-[0_0_20px_rgba(0,0,0,0.8)]">
                {post.title}
              </h1>
              <div className="flex items-center justify-center space-x-6 text-white/90">
                <div className="flex items-center">
                  <Calendar className="w-5 h-5 mr-2" />
                  {new Date(post.date).toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                  })}
                </div>
                <div className="flex items-center">
                  <Clock className="w-5 h-5 mr-2" />
                  {post.readTime}
                </div>
              </div>
            </ScrollReveal>
          </div>
        </section>

        {/* Article content */}
        <section className="py-16 bg-background-deep">
          <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
            {/* Back button and share */}
            <ScrollReveal>
              <div className="flex items-center justify-between mb-8">
                <Link
                  to="/blog"
                  className="inline-flex items-center text-neon hover:text-neon/80 transition-colors"
                >
                  <ArrowLeft className="w-5 h-5 mr-2" />
                  Back to Blog
                </Link>

                <button
                  onClick={handleShare}
                  className="inline-flex items-center px-4 py-2 bg-card-dark border border-border-muted rounded-lg text-foreground hover:bg-card-darker transition-colors"
                  aria-label="Share this article"
                >
                  <Share2 className="w-4 h-4 mr-2" />
                  Share
                </button>
              </div>
            </ScrollReveal>

            {/* Article metadata */}
            <ScrollReveal delay={100}>
              <div className="card-dark p-6 mb-8">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-foreground-muted text-sm mb-1">Written by</p>
                    <p className="text-foreground font-medium">{post.author}</p>
                  </div>
                  <div className="text-right">
                    <p className="text-foreground-muted text-sm mb-1">Published</p>
                    <p className="text-foreground font-medium">
                      {new Date(post.date).toLocaleDateString('en-US', {
                        year: 'numeric',
                        month: 'short',
                        day: 'numeric'
                      })}
                    </p>
                  </div>
                </div>
              </div>
            </ScrollReveal>

            {/* Article body */}
            <ScrollReveal delay={200}>
              <article
                ref={contentRef}
                className="prose prose-invert prose-xl max-w-none
                  prose-headings:font-heading prose-headings:font-bold prose-headings:tracking-tight

                  prose-h2:text-3xl prose-h2:text-foreground prose-h2:mb-8 prose-h2:mt-20
                  prose-h2:pb-2 prose-h2:font-bold prose-h2:border-b prose-h2:border-border-muted/30

                  prose-h3:text-2xl prose-h3:text-foreground prose-h3:mb-6 prose-h3:mt-12
                  prose-h3:font-bold prose-h3:leading-tight

                  prose-h4:text-xl prose-h4:text-foreground/90 prose-h4:mb-5 prose-h4:mt-10
                  prose-h4:font-semibold prose-h4:leading-snug

                  prose-p:text-foreground-muted prose-p:leading-[1.8] prose-p:mb-8 prose-p:text-lg
                  prose-p:max-w-none prose-p:first:mt-0

                  prose-a:text-neon prose-a:font-medium prose-a:underline prose-a:underline-offset-2
                  hover:prose-a:text-neon/80 prose-a:transition-colors

                  prose-strong:text-foreground prose-strong:font-bold

                  prose-ul:my-10 prose-ul:space-y-4 prose-ul:pl-0 prose-ul:max-w-none
                  prose-ol:my-10 prose-ol:space-y-4 prose-ol:pl-0 prose-ol:max-w-none

                  prose-li:text-lg prose-li:leading-[1.8] prose-li:pl-8 prose-li:relative
                  prose-li:before:content-['•'] prose-li:before:absolute prose-li:before:left-0
                  prose-li:before:text-neon prose-li:before:font-bold prose-li:before:text-xl
                  prose-li:before:leading-none

                  prose-code:text-neon prose-code:bg-card-darker/60 prose-code:px-3 prose-code:py-1
                  prose-code:rounded prose-code:text-sm prose-code:font-mono prose-code:border
                  prose-code:border-border-muted/30

                  prose-blockquote:border-l-4 prose-blockquote:border-neon prose-blockquote:pl-6
                  prose-blockquote:my-10 prose-blockquote:italic prose-blockquote:text-foreground-muted
                  prose-blockquote:bg-card-darker/30 prose-blockquote:p-6 prose-blockquote:rounded-r-lg

                  [&>h2]:first:mt-0
                  [&>p>a]:transition-all
                  [&>ul]:list-none
                  [&>ol]:list-none
                  [&>ol>li]:before:content-[counter(list-item)'.']
                  [&>ol]:counter-reset-[list-item]
                  [&>ol>li]:before:text-neon [&>ol>li]:before:font-bold [&>ol>li]:before:text-lg
                  [&>ol>li]:before:leading-none
                  
                  [&>p:first-child]:mt-0
                  [&>h2+*]:mt-6
                  [&>h3+*]:mt-4
                  [&>h4+*]:mt-3
                  [&>ul+*]:mt-6
                  [&>ol+*]:mt-6
                  [&>p+p]:mt-6"
              />
            </ScrollReveal>

            {/* CTA Section */}
            <ScrollReveal delay={300}>
              <div className="card-dark p-8 mt-12 text-center border-l-4 border-neon">
                <h3 className="font-heading font-bold text-2xl text-foreground mb-4">
                  Need help with {post.category.toLowerCase()} solutions?
                </h3>
                <p className="text-foreground-muted mb-6 max-w-2xl mx-auto">
                  Bay Area Affiliates provides expert IT services to businesses in Corpus Christi and the Coastal Bend. Let's discuss how we can help your business.
                </p>
                <Link
                  to="/contact"
                  className="btn-neon inline-block"
                >
                  Schedule a Free Consultation
                </Link>
              </div>
            </ScrollReveal>

            {/* Related posts */}
            <ScrollReveal delay={400}>
              <div className="mt-16">
                <h3 className="font-heading font-bold text-2xl text-foreground mb-6">
                  More Articles
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {blogPosts
                    .filter(p => p.id !== post.id)
                    .slice(0, 2)
                    .map((relatedPost) => (
                      <Link
                        key={relatedPost.id}
                        to={`/blog/${relatedPost.slug}`}
                        className="card-dark overflow-hidden group hover:shadow-neon transition-all duration-300"
                      >
                        <img
                          src={relatedPost.image}
                          alt={relatedPost.title}
                          className="w-full h-48 object-cover transition-transform duration-300 group-hover:scale-105"
                        />
                        <div className="p-6">
                          <div className="inline-block px-2 py-1 bg-neon/10 text-neon text-xs font-medium rounded mb-3">
                            {relatedPost.category}
                          </div>
                          <h4 className="font-heading font-bold text-lg text-foreground mb-2 group-hover:text-neon transition-colors">
                            {relatedPost.title}
                          </h4>
                          <p className="text-foreground-muted text-sm line-clamp-2">
                            {relatedPost.excerpt}
                          </p>
                        </div>
                      </Link>
                    ))}
                </div>
              </div>
            </ScrollReveal>
          </div>
        </section>
      </main>

      <Footer />

      {/* Scroll to Top Button */}
      <button
        onClick={scrollToTop}
        className={`fixed bottom-8 right-8 z-50 p-4 bg-neon text-neon-foreground rounded-full shadow-lg shadow-neon/50 transition-all duration-300 hover:scale-110 hover:shadow-neon ${showScrollTop ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-16 pointer-events-none'
          }`}
        aria-label="Scroll to top"
      >
        <ArrowUp className="w-6 h-6" />
      </button>
    </div>
  );
};

export default BlogPost;
