import { useEffect, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import { Helmet } from 'react-helmet';
import { getBlogPost } from '../utils/api';

const BACKEND_URL = process.env.REACT_APP_BACKEND_URL;

const BlogDetailPage = () => {
  const { id } = useParams();
  const [post, setPost] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    loadPost();
  }, [id]);

  useEffect(() => {
    if (post) {
      // Update page title
      document.title = `${post.title} | RH Elektronik Blog`;
      
      // Update meta description
      const metaDescription = document.querySelector('meta[name="description"]');
      if (metaDescription) {
        metaDescription.setAttribute('content', post.meta_description || post.excerpt || post.title);
      }
    }
  }, [post]);

  const loadPost = async () => {
    try {
      const response = await getBlogPost(id);
      setPost(response.data);
    } catch (error) {
      console.error('Error loading post:', error);
      setError('Artikel tidak ditemukan');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-xl text-gray-600">Loading...</div>
      </div>
    );
  }

  if (error || !post) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <p className="text-xl text-red-600 mb-4">{error || 'Artikel tidak ditemukan'}</p>
          <Link to="/blog" className="text-blue-600 hover:text-blue-700">
            ← Kembali ke Blog
          </Link>
        </div>
      </div>
    );
  }

  const pageUrl = `${window.location.origin}/blog/${post.id}`;
  const siteName = "RH Elektronik";
  const siteUrl = window.location.origin;

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Structured Data for Google */}
      <Helmet>
        <title>{post.title} | RH Elektronik Blog</title>
        <meta name="description" content={post.meta_description || post.excerpt || post.title} />
        {post.meta_keywords && <meta name="keywords" content={post.meta_keywords} />}
        <link rel="canonical" href={pageUrl} />
        
        {/* Open Graph / Facebook */}
        <meta property="og:type" content="article" />
        <meta property="og:url" content={pageUrl} />
        <meta property="og:title" content={post.title} />
        <meta property="og:description" content={post.meta_description || post.excerpt || post.title} />
        {post.featured_image && <meta property="og:image" content={post.featured_image} />}
        <meta property="og:site_name" content={siteName} />
        <meta property="article:published_time" content={post.created_at} />
        <meta property="article:author" content={post.author} />
        
        {/* Twitter */}
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:url" content={pageUrl} />
        <meta name="twitter:title" content={post.title} />
        <meta name="twitter:description" content={post.meta_description || post.excerpt || post.title} />
        {post.featured_image && <meta name="twitter:image" content={post.featured_image} />}
        
        {/* Structured Data */}
        <script type="application/ld+json">
          {JSON.stringify({
            "@context": "https://schema.org",
            "@type": "BlogPosting",
            "headline": post.title,
            "description": post.meta_description || post.excerpt,
            "image": post.featured_image,
            "author": {
              "@type": "Person",
              "name": post.author
            },
            "publisher": {
              "@type": "Organization",
              "name": siteName,
              "logo": {
                "@type": "ImageObject",
                "url": `${siteUrl}/assets/img/logo1.png`
              }
            },
            "datePublished": post.created_at,
            "dateModified": post.updated_at,
            "mainEntityOfPage": {
              "@type": "WebPage",
              "@id": pageUrl
            }
          })}
        </script>
      </Helmet>

      {/* Header */}
      <header className="bg-white border-b sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-5 py-4 flex justify-between items-center">
          <Link to="/" className="flex items-center gap-3">
            <img src="/assets/img/logo1.png" alt="Logo" className="h-12" />
            <div>
              <div className="text-xl font-bold text-gray-900">
                <strong className="text-blue-600">RH</strong> Elektronik
              </div>
            </div>
          </Link>

          <Link 
            to="/blog"
            className="text-gray-700 font-semibold hover:text-blue-600"
          >
            ← Kembali ke Blog
          </Link>
        </div>
      </header>

      {/* Ad Zone - Top Header (728x90) */}
      <div className="bg-gray-100 border-b">
        <div className="max-w-7xl mx-auto px-5 py-4">
          <div className="bg-white border-2 border-dashed border-gray-300 rounded-lg p-4 text-center">
            <div className="text-gray-400 text-sm font-semibold">AD SPACE 728x90 (Leaderboard)</div>
            <div className="text-gray-300 text-xs mt-1">Pasang kode iklan Google AdSense di sini</div>
            {/* Tempat kode AdSense */}
          </div>
        </div>
      </div>

      {/* Featured Image */}
      {post.featured_image && (
        <div className="w-full h-96 overflow-hidden bg-gray-200">
          <img 
            src={post.featured_image}
            alt={post.title}
            className="w-full h-full object-cover"
          />
        </div>
      )}

      {/* Main Content Container */}
      <div className="max-w-7xl mx-auto px-5 py-12">
        <div className="grid lg:grid-cols-12 gap-8">
          
          {/* Main Article Column */}
          <article className="lg:col-span-8">
            <div className="bg-white rounded-2xl shadow-lg p-8 md:p-12">
              {/* Meta Info */}
              <div className="flex items-center gap-4 text-sm text-gray-500 mb-6">
                <span className="font-medium text-blue-600">{post.author}</span>
                <span>•</span>
                <span>{new Date(post.created_at).toLocaleDateString('id-ID', {
                  year: 'numeric',
                  month: 'long',
                  day: 'numeric'
                })}</span>
                {post.views > 0 && (
                  <>
                    <span>•</span>
                    <span>👁️ {post.views} views</span>
                  </>
                )}
              </div>

              {/* Title */}
              <h1 className="text-4xl md:text-5xl font-extrabold text-gray-900 mb-8 leading-tight">
                {post.title}
              </h1>

              {/* Excerpt */}
              {post.excerpt && (
                <p className="text-xl text-gray-600 mb-8 italic border-l-4 border-blue-600 pl-6">
                  {post.excerpt}
                </p>
              )}

              {/* Ad Zone - In-Content Top (336x280) */}
              <div className="my-8 bg-gray-50 border-2 border-dashed border-gray-300 rounded-lg p-4">
                <div className="text-center">
                  <div className="text-gray-400 text-sm font-semibold">AD SPACE 336x280 (Rectangle)</div>
                  <div className="text-gray-300 text-xs mt-1">In-content advertisement</div>
                  {/* Tempat kode AdSense */}
                </div>
              </div>

              {/* Content */}
              <div 
                className="blog-content prose prose-lg max-w-none"
                dangerouslySetInnerHTML={{ __html: post.content }}
              />

              {/* Ad Zone - In-Content Bottom (300x250) */}
              <div className="mt-12 mb-8 bg-gray-50 border-2 border-dashed border-gray-300 rounded-lg p-4">
                <div className="text-center">
                  <div className="text-gray-400 text-sm font-semibold">AD SPACE 300x250 (Medium Rectangle)</div>
                  <div className="text-gray-300 text-xs mt-1">Bottom content advertisement</div>
                  {/* Tempat kode AdSense */}
                </div>
              </div>

              {/* Social Share */}
              <div className="mt-12 pt-8 border-t">
                <h3 className="text-lg font-bold text-gray-900 mb-4">📢 Bagikan Artikel Ini:</h3>
                <div className="flex gap-3 flex-wrap">
                  <a 
                    href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(pageUrl)}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition font-semibold"
                  >
                    Facebook
                  </a>
                  <a 
                    href={`https://twitter.com/intent/tweet?url=${encodeURIComponent(pageUrl)}&text=${encodeURIComponent(post.title)}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="px-6 py-3 bg-sky-500 text-white rounded-lg hover:bg-sky-600 transition font-semibold"
                  >
                    Twitter
                  </a>
                  <a 
                    href={`https://wa.me/?text=${encodeURIComponent(post.title + ' ' + pageUrl)}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="px-6 py-3 bg-green-500 text-white rounded-lg hover:bg-green-600 transition font-semibold"
                  >
                    WhatsApp
                  </a>
                  <a 
                    href={`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(pageUrl)}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="px-6 py-3 bg-blue-700 text-white rounded-lg hover:bg-blue-800 transition font-semibold"
                  >
                    LinkedIn
                  </a>
                </div>
              </div>
            </div>

            {/* CTA Section */}
            <div className="mt-12 bg-gradient-to-br from-blue-50 to-blue-100 rounded-2xl p-8 text-center">
              <h3 className="text-2xl font-bold text-gray-900 mb-4">
                Butuh Bantuan Service Elektronik?
              </h3>
              <p className="text-gray-700 mb-6">
                Tim teknisi profesional RH Elektronik siap membantu Anda
              </p>
              <div className="flex justify-center gap-4 flex-wrap">
                <a 
                  href="https://wa.me/6281554333316"
                  className="px-8 py-3 bg-green-500 text-white font-bold rounded-xl hover:bg-green-600 transition"
                >
                  📱 Hubungi WhatsApp
                </a>
                <Link 
                  to="/"
                  className="px-8 py-3 bg-blue-600 text-white font-bold rounded-xl hover:bg-blue-700 transition"
                >
                  🏠 Kembali ke Home
                </Link>
              </div>
            </div>
          </article>

          {/* Sidebar - Ad Zone */}
          <aside className="lg:col-span-4">
            <div className="lg:sticky lg:top-24 space-y-6">
              
              {/* Ad Zone - Sidebar Top (300x600) */}
              <div className="bg-white rounded-2xl shadow-lg p-6">
                <div className="bg-gray-50 border-2 border-dashed border-gray-300 rounded-lg p-8 text-center" style={{minHeight: '600px'}}>
                  <div className="text-gray-400 font-semibold mb-2">AD SPACE</div>
                  <div className="text-gray-400 text-sm">300x600</div>
                  <div className="text-gray-300 text-xs mt-2">(Half Page / Wide Skyscraper)</div>
                  <div className="text-gray-300 text-xs mt-4">Pasang Google AdSense atau iklan banner di sini</div>
                  {/* Tempat kode AdSense */}
                </div>
              </div>

              {/* Ad Zone - Sidebar Middle (300x250) */}
              <div className="bg-white rounded-2xl shadow-lg p-6">
                <div className="bg-gray-50 border-2 border-dashed border-gray-300 rounded-lg p-8 text-center" style={{minHeight: '250px'}}>
                  <div className="text-gray-400 font-semibold mb-2">AD SPACE</div>
                  <div className="text-gray-400 text-sm">300x250</div>
                  <div className="text-gray-300 text-xs mt-2">(Medium Rectangle)</div>
                  {/* Tempat kode AdSense */}
                </div>
              </div>

              {/* Related Services */}
              <div className="bg-white rounded-2xl shadow-lg p-6">
                <h3 className="font-bold text-lg text-gray-900 mb-4">🔧 Layanan Kami</h3>
                <ul className="space-y-3">
                  <li>
                    <Link to="/" className="text-blue-600 hover:text-blue-700 hover:underline">
                      Service AC & Kulkas
                    </Link>
                  </li>
                  <li>
                    <Link to="/" className="text-blue-600 hover:text-blue-700 hover:underline">
                      Perbaikan Mesin Cuci
                    </Link>
                  </li>
                  <li>
                    <Link to="/" className="text-blue-600 hover:text-blue-700 hover:underline">
                      Klaim Garansi Resmi
                    </Link>
                  </li>
                </ul>
              </div>
            </div>
          </aside>
        </div>
      </div>

      {/* Ad Zone - Bottom (728x90) */}
      <div className="bg-gray-100 border-t">
        <div className="max-w-7xl mx-auto px-5 py-4">
          <div className="bg-white border-2 border-dashed border-gray-300 rounded-lg p-4 text-center">
            <div className="text-gray-400 text-sm font-semibold">AD SPACE 728x90 (Bottom Leaderboard)</div>
            <div className="text-gray-300 text-xs mt-1">Bottom page advertisement</div>
            {/* Tempat kode AdSense */}
          </div>
        </div>
      </div>

      {/* Footer */}
      <footer className="bg-gray-900 text-gray-400 text-center py-10 mt-20">
        <p>© 2026 CV RH Elektronik - Authorized Service Center</p>
      </footer>
    </div>
  );
};

export default BlogDetailPage;
