import React, { useState, useEffect } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { Calendar, User, Tag, ArrowLeft, Eye, Share2, ArrowRight } from 'lucide-react';
import blogService, { BlogPost } from '../services/blogService';
import Loading from '../../../shared/components/Loading';
import { createSanitizedHtml } from '../../../shared/utils/htmlSanitizer';
import { useTheme } from '../../../shared/contexts/ThemeContext';
import { getThemeBackgroundClasses, getThemeTextClasses, getThemeCardClasses } from '../../../shared/utils/themeUtils';

const BlogDetailPage: React.FC = () => {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const { theme } = useTheme();
  const [post, setPost] = useState<BlogPost | null>(null);
  const [loading, setLoading] = useState(true);
  const [relatedPosts, setRelatedPosts] = useState<BlogPost[]>([]);
  
  const bgClasses = getThemeBackgroundClasses(theme.theme_layout_mode);
  const textClasses = getThemeTextClasses(theme.theme_layout_mode);
  const cardClasses = getThemeCardClasses(theme.theme_layout_mode);

  useEffect(() => {
    if (slug) {
      fetchPost();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [slug]);

  const fetchPost = async () => {
    try {
      setLoading(true);
      const response = await blogService.getBlogPostBySlug(slug!);
      
      if (response.status === 'success' && response.data) {
        const postData = response.data.post;
        setPost(postData);

        // Set meta tags
        if (postData.meta_title) {
          document.title = postData.meta_title;
        }
        if (postData.meta_description) {
          let metaDescription = document.querySelector('meta[name="description"]');
          if (!metaDescription) {
            metaDescription = document.createElement('meta');
            metaDescription.setAttribute('name', 'description');
            document.head.appendChild(metaDescription);
          }
          metaDescription.setAttribute('content', postData.meta_description);
        }

        // Fetch related posts
        if (postData.tags && postData.tags.length > 0) {
          fetchRelatedPosts(postData.tags[0]);
        }
      }
    } catch (error: unknown) {
      console.error('Error fetching blog post:', error);
      const isApiError = (e: unknown): e is { response?: { status?: number } } => {
        return typeof e === 'object' && e !== null;
      };
      if (isApiError(error) && error.response?.status === 404) {
        navigate('/blog');
      }
    } finally {
      setLoading(false);
    }
  };

  const fetchRelatedPosts = async (tag: string) => {
    try {
      const response = await blogService.getBlogPosts({
        page: 1,
        limit: 3,
        tag,
        published_only: true,
      });

      if (response.status === 'success' && response.data) {
        // Filter out current post
        const related = response.data.posts.filter((p: BlogPost) => p.slug !== slug);
        setRelatedPosts(related.slice(0, 3));
      }
    } catch (error) {
      console.error('Error fetching related posts:', error);
    }
  };

  const formatDate = (dateString?: string) => {
    if (!dateString) return '';
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  const handleShare = async () => {
    if (navigator.share && post) {
      try {
        await navigator.share({
          title: post.title,
          text: post.excerpt,
          url: window.location.href,
        });
      } catch (error) {
        // User cancelled or error occurred
      }
    } else {
      // Fallback: copy to clipboard
      navigator.clipboard.writeText(window.location.href);
      alert('Link copied to clipboard!');
    }
  };

  if (loading) {
    return <Loading />;
  }

  if (!post) {
    return (
      <div className={`min-h-screen ${bgClasses} flex items-center justify-center`}>
        <div className="text-center">
          <h1 className={`text-2xl font-bold mb-4 ${textClasses.primary}`}>Post not found</h1>
          <Link to="/blog" className="text-[var(--luxury-gold)] hover:underline">
            Back to Blog
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className={`min-h-screen ${bgClasses} w-full`} style={{ width: '100vw', position: 'relative', left: '50%', right: '50%', marginLeft: '-50vw', marginRight: '-50vw', marginTop: '-1.5rem', marginBottom: '-1.5rem' }}>
      {/* Hero Section with Featured Image */}
      {post.featured_image && (
        <div className="relative w-full h-64 sm:h-80 lg:h-96 overflow-hidden">
          <img
            src={post.featured_image}
            alt={post.title}
            className="w-full h-full object-cover"
          />
          <div className="absolute inset-0 bg-gradient-to-t from-black via-black/50 to-transparent"></div>
        </div>
      )}

      {/* Main Content */}
      <div className="w-full py-8 sm:py-12 lg:py-16">
        <div className="w-full max-w-[1920px] mx-auto px-3 sm:px-4 md:px-6 lg:px-8 xl:px-12 2xl:px-16 3xl:px-20">
          <div className="max-w-4xl mx-auto">
        {/* Back Button */}
        <Link
          to="/blog"
          className={`inline-flex items-center gap-2 ${textClasses.muted} hover:text-[var(--luxury-gold)] transition-colors mb-8`}
        >
          <ArrowLeft className="w-4 h-4" />
          <span>Back to Blog</span>
        </Link>

        {/* Article Header */}
        <div className="mb-8">
          {post.tags && post.tags.length > 0 && (
            <div className="flex flex-wrap gap-2 mb-4">
              {post.tags.map((tag) => (
                <Link
                  key={tag}
                  to={`/blog?tag=${encodeURIComponent(tag)}`}
                  className="inline-flex items-center gap-1 px-3 py-1 bg-[var(--luxury-gold)]/10 text-[var(--luxury-gold)] rounded-full text-sm font-medium hover:bg-[var(--luxury-gold)]/20 transition-colors"
                >
                  <Tag className="w-3 h-3" />
                  {tag}
                </Link>
              ))}
            </div>
          )}

          <h1 className="text-3xl sm:text-4xl lg:text-5xl font-display font-bold text-white mb-6 leading-tight">
            {post.title}
          </h1>

          {post.excerpt && (
            <p className="text-xl text-gray-300 mb-6 font-light leading-relaxed">
              {post.excerpt}
            </p>
          )}

          <div className={`flex flex-wrap items-center gap-6 text-sm ${textClasses.muted} pb-6 border-b border-[var(--luxury-gold)]/20`}>
            {post.published_at && (
              <div className="flex items-center gap-2">
                <Calendar className="w-4 h-4" />
                <span>{formatDate(post.published_at)}</span>
              </div>
            )}
            {post.author_name && (
              <div className="flex items-center gap-2">
                <User className="w-4 h-4" />
                <span>{post.author_name}</span>
              </div>
            )}
            <div className="flex items-center gap-2">
              <Eye className="w-4 h-4" />
              <span>{post.views_count} views</span>
            </div>
            <button
              onClick={handleShare}
              className="flex items-center gap-2 text-[var(--luxury-gold)] hover:text-[var(--luxury-gold-light)] transition-colors"
            >
              <Share2 className="w-4 h-4" />
              <span>Share</span>
            </button>
          </div>
        </div>

        {/* Article Content */}
        <article className={`prose ${theme.theme_layout_mode === 'light' ? 'prose-slate' : 'prose-invert'} prose-lg max-w-none mb-12
          prose-headings:font-elegant prose-headings:font-semibold
          prose-h2:text-3xl prose-h2:mt-12 prose-h2:mb-6 prose-h2:border-b prose-h2:border-[var(--luxury-gold)]/20 prose-h2:pb-3
          prose-h3:text-2xl prose-h3:mt-8 prose-h3:mb-4
          prose-p:font-light prose-p:leading-relaxed prose-p:mb-6
          prose-ul:font-light prose-ul:my-6
          prose-ol:font-light prose-ol:my-6
          prose-li:mb-2
          prose-strong:text-[var(--luxury-gold)] prose-strong:font-medium
          prose-a:text-[var(--luxury-gold)] prose-a:no-underline hover:prose-a:underline
          prose-img:rounded-xl prose-img:shadow-2xl`}
          style={{ color: theme.theme_layout_mode === 'light' ? '#374151' : '#d1d5db' }}
        >
          <div
            dangerouslySetInnerHTML={createSanitizedHtml(
              post.content || '<p>No content available.</p>'
            )}
          />
        </article>

        {/* Luxury Sections */}
        {post.sections && post.sections.length > 0 && (
          <div className="space-y-16 mb-12">
            {post.sections
              .filter((section) => section.is_visible !== false) // Only show visible sections
              .map((section, index) => (
              <div key={index}>
                {/* Hero Section */}
                {section.type === 'hero' && (
                  <div className="relative rounded-3xl overflow-hidden border-2 border-[var(--luxury-gold)]/20 shadow-2xl">
                    {section.image && (
                      <div className="absolute inset-0">
                        <img src={section.image} alt={section.title} className="w-full h-full object-cover" />
                        <div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/50 to-transparent"></div>
                      </div>
                    )}
                    <div className="relative px-8 py-16 md:px-16 md:py-24 text-center">
                      {section.title && (
                        <h2 className="text-4xl md:text-5xl lg:text-6xl font-serif font-bold text-white mb-6">
                          {section.title}
                        </h2>
                      )}
                      {section.content && (
                        <p className={`text-xl md:text-2xl ${textClasses.secondary} font-light leading-relaxed max-w-3xl mx-auto`}>
                          {section.content}
                        </p>
                      )}
                    </div>
                  </div>
                )}

                {/* Text Section */}
                {section.type === 'text' && (
                  <div className={`bg-gradient-to-br from-[#1a1a1a] to-[#0f0f0f] rounded-3xl border-2 border-[var(--luxury-gold)]/20 p-8 md:p-12 shadow-xl ${
                    section.alignment === 'center' ? 'text-center' : section.alignment === 'right' ? 'text-right' : 'text-left'
                  }`}>
                    {section.title && (
                      <h3 className="text-3xl md:text-4xl font-serif font-bold text-white mb-6">
                        {section.title}
                      </h3>
                    )}
                    {section.content && (
                      <div
                        className="text-gray-300 font-light leading-relaxed text-lg"
                        dangerouslySetInnerHTML={createSanitizedHtml(section.content)}
                      />
                    )}
                  </div>
                )}

                {/* Image Section */}
                {section.type === 'image' && section.image && (
                  <div className="rounded-3xl overflow-hidden border-2 border-[var(--luxury-gold)]/20 shadow-2xl">
                    <img src={section.image} alt={section.title || 'Blog image'} className="w-full h-auto" />
                    {section.title && (
                      <div className={`${cardClasses} px-6 py-4 border-t border-[var(--luxury-gold)]/20`}>
                        <p className={`${textClasses.muted} text-sm font-light italic text-center`}>{section.title}</p>
                      </div>
                    )}
                  </div>
                )}

                {/* Gallery Section */}
                {section.type === 'gallery' && section.images && section.images.length > 0 && (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {section.images.map((img, imgIndex) => (
                      <div key={imgIndex} className="rounded-2xl overflow-hidden border-2 border-[var(--luxury-gold)]/20 shadow-xl group hover:border-[var(--luxury-gold)]/50 transition-all">
                        <img src={img} alt={`Gallery image ${imgIndex + 1}`} className="w-full h-64 object-cover group-hover:scale-110 transition-transform duration-500" />
                      </div>
                    ))}
                  </div>
                )}

                {/* Quote Section */}
                {section.type === 'quote' && (
                  <div className="relative bg-gradient-to-br from-[#1a1a1a] to-[#0f0f0f] rounded-3xl border-2 border-[var(--luxury-gold)]/30 p-8 md:p-12 shadow-2xl">
                    <div className="absolute top-6 left-6 text-6xl text-[var(--luxury-gold)]/20 font-serif">"</div>
                    {section.quote && (
                      <blockquote className="text-2xl md:text-3xl font-serif font-light text-white italic mb-6 relative z-10 pl-8">
                        {section.quote}
                      </blockquote>
                    )}
                    {section.author && (
                      <cite className="text-[var(--luxury-gold)] text-lg font-medium not-italic block text-right">
                        — {section.author}
                      </cite>
                    )}
                  </div>
                )}

                {/* Features Section */}
                {section.type === 'features' && section.features && (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {section.features.map((feature, featIndex) => (
                      <div key={featIndex} className="bg-gradient-to-br from-[#1a1a1a] to-[#0f0f0f] rounded-2xl border-2 border-[var(--luxury-gold)]/20 p-6 shadow-xl hover:border-[var(--luxury-gold)]/50 transition-all">
                        {feature.icon && (
                          <div className="text-4xl mb-4">{feature.icon}</div>
                        )}
                        <h4 className="text-xl font-bold text-white mb-3">{feature.title}</h4>
                        <p className="text-gray-300 font-light leading-relaxed">{feature.description}</p>
                      </div>
                    ))}
                  </div>
                )}

                {/* CTA Section */}
                {section.type === 'cta' && (
                  <div className="relative bg-gradient-to-br from-[var(--luxury-gold)]/10 via-[var(--luxury-gold-dark)]/5 to-[var(--luxury-gold)]/10 rounded-3xl border-2 border-[var(--luxury-gold)]/30 p-8 md:p-12 text-center shadow-2xl">
                    {section.title && (
                      <h3 className="text-3xl md:text-4xl font-serif font-bold text-white mb-4">
                        {section.title}
                      </h3>
                    )}
                    {section.content && (
                      <p className="text-xl text-gray-300 font-light mb-8 max-w-2xl mx-auto">
                        {section.content}
                      </p>
                    )}
                    {section.cta_text && section.cta_link && (
                      <a
                        href={section.cta_link}
                        className="inline-flex items-center gap-3 px-8 py-4 bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] text-[#0f0f0f] font-semibold rounded-xl hover:from-[var(--luxury-gold-light)] hover:to-[var(--luxury-gold)] transition-all shadow-lg hover:shadow-xl hover:scale-105"
                      >
                        {section.cta_text}
                        <ArrowRight className="w-5 h-5" />
                      </a>
                    )}
                  </div>
                )}

                {/* Video Section */}
                {section.type === 'video' && section.video_url && (
                  <div className="rounded-3xl overflow-hidden border-2 border-[var(--luxury-gold)]/20 shadow-2xl bg-black">
                    <div className="aspect-video">
                      <iframe
                        src={section.video_url.replace('watch?v=', 'embed/').replace('vimeo.com/', 'player.vimeo.com/video/')}
                        className="w-full h-full"
                        allowFullScreen
                        title="Blog video"
                      />
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}

        {/* Related Posts */}
        {relatedPosts.length > 0 && (
          <div className="mt-16 pt-12 border-t border-[var(--luxury-gold)]/20">
            <h2 className={`text-2xl sm:text-3xl font-bold ${textClasses.primary} mb-8`}>Related Posts</h2>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {relatedPosts.map((relatedPost) => (
                <Link
                  key={relatedPost.id}
                  to={`/blog/${relatedPost.slug}`}
                  className="group bg-gradient-to-br from-[#1a1a1a] to-[#0f0f0f] rounded-xl border border-[var(--luxury-gold)]/20 overflow-hidden hover:border-[var(--luxury-gold)]/50 transition-all duration-300"
                >
                  {relatedPost.featured_image && (
                    <div className="relative h-40 overflow-hidden">
                      <img
                        src={relatedPost.featured_image}
                        alt={relatedPost.title}
                        className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
                      />
                    </div>
                  )}
                  <div className="p-4">
                    <h3 className={`text-lg font-bold ${textClasses.primary} mb-2 group-hover:text-[var(--luxury-gold)] transition-colors line-clamp-2`}>
                      {relatedPost.title}
                    </h3>
                    {relatedPost.excerpt && (
                      <p className={`${textClasses.muted} text-sm line-clamp-2 font-light`}>
                        {relatedPost.excerpt}
                      </p>
                    )}
                  </div>
                </Link>
              ))}
            </div>
          </div>
        )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default BlogDetailPage;

