import React, { useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Helmet } from 'react-helmet-async';
import { BlogPost as BlogPostComponent } from "./BlogPost";
import { blogPosts } from "../data/blogPosts";
import { findPostBySlug } from "../utils/slugify";

export const BlogPostPage: React.FC = () => {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const [isMenuOpen, setIsMenuOpen] = useState(false);

  const post = findPostBySlug(blogPosts, slug || '');

  // Generate dynamic meta tags based on the blog post
  const generateMetaTags = () => {
    if (!post) return null;
    
    const postUrl = `https://febinjoy.netlify.app/blog/${slug}`;
    const postImage = `https://febinjoy.netlify.app/og-image.jpg`;
    
    return (
      <Helmet>
        <title>{post.title} | Febin Joy – SEO Expert Kerala</title>
        <meta name="description" content={post.excerpt} />
        <meta name="keywords" content={`${post.tags.join(', ')}, seo expert kerala, seo blog, digital marketing, ${post.category.toLowerCase()}`} />
        <meta name="author" content={post.author} />
        <meta name="robots" content="index, follow" />
        <link rel="canonical" href={postUrl} />
        
        {/* Open Graph Meta Tags */}
        <meta property="og:title" content={post.title} />
        <meta property="og:description" content={post.excerpt} />
        <meta property="og:type" content="article" />
        <meta property="og:url" content={postUrl} />
        <meta property="og:image" content={postImage} />
        <meta property="og:locale" content="en_IN" />
        <meta property="og:site_name" content="Febin Joy - SEO Expert Kerala" />
        <meta property="article:author" content={post.author} />
        <meta property="article:published_time" content={post.publishDate} />
        <meta property="article:section" content={post.category} />
        {post.tags.map((tag: string, index: number) => (
          <meta key={index} property="article:tag" content={tag} />
        ))}
        
        {/* Twitter Card Meta Tags */}
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:title" content={post.title} />
        <meta name="twitter:description" content={post.excerpt} />
        <meta name="twitter:image" content={postImage} />
        
        {/* Schema.org Structured Data */}
        <script type="application/ld+json">
          {JSON.stringify({
            "@context": "https://schema.org",
            "@type": "BlogPosting",
            "headline": post.title,
            "description": post.excerpt,
            "url": postUrl,
            "datePublished": post.publishDate,
            "dateModified": post.publishDate,
            "author": {
              "@type": "Person",
              "name": post.author,
              "url": "https://febinjoy.netlify.app"
            },
            "publisher": {
              "@type": "Person",
              "name": "Febin Joy",
              "url": "https://febinjoy.netlify.app"
            },
            "mainEntityOfPage": {
              "@type": "WebPage",
              "@id": postUrl
            },
            "image": postImage,
            "articleSection": post.category,
            "keywords": post.tags.join(', '),
            "wordCount": post.content.replace(/<[^>]*>/g, '').split(' ').length,
            "inLanguage": "en-IN",
            "about": post.tags
          })}
        </script>
      </Helmet>
    );
  };

  if (!post) {
    return (
      <div className="min-h-screen bg-gray-50">
        <main className="flex items-center justify-center min-h-screen">
          <div className="text-center">
            <h2 className="mb-4 text-4xl font-bold text-gray-800">Post Not Found</h2>
            <p className="mb-8 text-gray-600">The blog post you're looking for doesn't exist.</p>
            <button
              onClick={() => navigate("/blog")}
              className="px-6 py-3 text-white transition-colors bg-blue-600 rounded-lg hover:bg-blue-700"
            >
              Back to Blog
            </button>
          </div>
        </main>
      </div>
    );
  }

  const handleBackToBlog = () => {
    navigate("/blog");
  };

  const scrollToSection = (sectionId: string) => {
    if (sectionId === "blog") {
      navigate("/blog");
      return;
    }
    navigate("/");
    setTimeout(() => {
      const element = document.getElementById(sectionId);
      if (element) {
        element.scrollIntoView({ behavior: "smooth" });
      }
    }, 100);
  };

  return (
    <>
      {generateMetaTags()}
      <div className="min-h-screen bg-gray-50">
      {/* Navigation */}
      <nav className="fixed top-0 left-0 right-0 z-50 shadow-sm bg-white/95 backdrop-blur-md">
        <div className="px-4 mx-auto max-w-7xl sm:px-6 lg:px-8">
          <div className="flex items-center justify-between py-4">
            <button
              onClick={() => navigate("/")}
              className="text-2xl font-bold text-transparent transition-opacity bg-gradient-to-r from-blue-600 to-green-600 bg-clip-text hover:opacity-80"
              aria-label="Go to homepage"
            >
              Febin Joy
            </button>

            <div className="hidden space-x-8 md:flex">
              {[
                "home",
                "about",
                "experience",
                "skills",
                "education",
                "blog",
                "contact",
              ].map((section) => (
                <button
                  key={section}
                  onClick={() => scrollToSection(section)}
                  className="text-gray-600 capitalize transition-all duration-300 hover:text-blue-600"
                >
                  {section}
                </button>
              ))}
            </div>

            <button
              className="md:hidden"
              onClick={() => setIsMenuOpen(!isMenuOpen)}
              aria-label={isMenuOpen ? "Close navigation menu" : "Open navigation menu"}
              aria-expanded={isMenuOpen}
            >
              <div className="flex flex-col justify-center w-6 h-6 space-y-1">
                <span
                  className={`block h-0.5 bg-gray-600 transition-transform ${
                    isMenuOpen ? "rotate-45 translate-y-1.5" : ""
                  }`}
                ></span>
                <span
                  className={`block h-0.5 bg-gray-600 transition-opacity ${
                    isMenuOpen ? "opacity-0" : ""
                  }`}
                ></span>
                <span
                  className={`block h-0.5 bg-gray-600 transition-transform ${
                    isMenuOpen ? "-rotate-45 -translate-y-1.5" : ""
                  }`}
                ></span>
              </div>
            </button>
          </div>

          {isMenuOpen && (
            <div className="py-4 border-t md:hidden">
              {[
                "home",
                "about",
                "experience",
                "skills",
                "education",
                "blog",
                "contact",
              ].map((section) => (
                <button
                  key={section}
                  onClick={() => scrollToSection(section)}
                  className="block w-full py-2 text-left text-gray-600 capitalize transition-colors hover:text-blue-600"
                >
                  {section}
                </button>
              ))}
            </div>
          )}
        </div>
      </nav>

      <main>
        {/* Blog Post Content */}
      <section className="pt-24 pb-20">
        <div className="px-4 mx-auto max-w-7xl sm:px-6 lg:px-8">
          <BlogPostComponent post={post} onBack={handleBackToBlog} />
        </div>
      </section>
      </main>

      {/* Footer */}
      <footer className="py-8 text-white bg-gray-900">
        <div className="px-4 mx-auto text-center max-w-7xl sm:px-6 lg:px-8">
          <p className="mb-4">
            © 2026 Febin Joy – SEO Expert in Kerala. All Rights Reserved.
          </p>
          <p className="text-sm text-gray-400">
            Helping businesses achieve top rankings and sustainable organic
            growth through strategic SEO optimization.
          </p>
        </div>
      </footer>
      </div>
    </>
  );
};
