import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Calendar, User, Tag, Search, ArrowRight, Eye, Sparkles, BookOpen } from 'lucide-react';
import blogService, { BlogPost } from '../services/blogService';
import Loading from '../../../shared/components/Loading';
import { useTheme } from '../../../shared/contexts/ThemeContext';
import { getThemeBackgroundClasses, getThemeHeroBackgroundClasses, getThemeTextClasses, getThemeCardClasses, getThemeInputClasses } from '../../../shared/utils/themeUtils';
import Pagination from '../../../shared/components/Pagination';

const BlogPage: React.FC = () => {
  const { theme } = useTheme();
  const [posts, setPosts] = useState<BlogPost[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [total, setTotal] = useState(0);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedTag, setSelectedTag] = useState<string | null>(null);
  const [allTags, setAllTags] = useState<string[]>([]);

  useEffect(() => {
    fetchPosts();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, searchTerm, selectedTag]);

  const fetchPosts = async () => {
    try {
      setLoading(true);
      const response = await blogService.getBlogPosts({
        page: currentPage,
        limit: 10,
        search: searchTerm || undefined,
        tag: selectedTag || undefined,
        published_only: true,
      });

      if (response.status === 'success' && response.data) {
        setPosts(response.data.posts);
        setTotalPages(response.data.pagination.pages);
        setTotal(response.data.pagination.total);

        // Use all_tags from API response if available, otherwise extract from current page
        if (response.data.all_tags && Array.isArray(response.data.all_tags)) {
          setAllTags(response.data.all_tags);
        } else {
          // Fallback: extract tags from current page posts
          const tags = new Set<string>();
          response.data.posts.forEach((post: BlogPost) => {
            post.tags?.forEach(tag => tags.add(tag));
          });
          setAllTags(Array.from(tags));
        }
      }
    } catch (error: unknown) {
      console.error('Error fetching blog posts:', error);
    } finally {
      setLoading(false);
    }
  };

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

  if (loading && posts.length === 0) {
    return <Loading />;
  }

  const bgClasses = getThemeBackgroundClasses(theme.theme_layout_mode);
  const heroBgClasses = getThemeHeroBackgroundClasses(theme.theme_layout_mode);
  const textClasses = getThemeTextClasses(theme.theme_layout_mode);
  const cardClasses = getThemeCardClasses(theme.theme_layout_mode);
  const inputClasses = getThemeInputClasses(theme.theme_layout_mode);

  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 */}
      <div className={`w-full ${heroBgClasses} pt-6 sm:pt-7 md:pt-8 overflow-hidden relative`}>
        {/* Background Effects */}
        <div className="absolute inset-0 opacity-10">
          <div className="absolute top-10 left-10 w-32 sm:w-48 h-32 sm:h-48 bg-[var(--luxury-gold)] rounded-full blur-3xl"></div>
          <div className="absolute bottom-10 right-10 w-40 sm:w-64 h-40 sm:h-64 bg-[var(--luxury-gold-dark)] rounded-full blur-3xl"></div>
        </div>
        <div className="absolute top-0 left-0 w-full h-px bg-gradient-to-r from-transparent via-[var(--luxury-gold)]/50 to-transparent"></div>
        
        <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 py-4 sm:py-5 md:py-6 relative z-10">
          <div className="max-w-2xl mx-auto text-center px-2">
            <div className="flex justify-center mb-2 sm:mb-3 md:mb-4">
              <div className="relative group">
                <div className="absolute inset-0 bg-gradient-to-br from-[var(--luxury-gold)] via-[var(--luxury-gold-light)] to-[var(--luxury-gold-dark)] rounded-xl blur-lg opacity-40 group-hover:opacity-60 transition-opacity duration-500"></div>
                <div className={`relative p-2 sm:p-2.5 md:p-3 ${cardClasses} rounded-lg border-2 border-[var(--luxury-gold)]/40 backdrop-blur-sm shadow-xl shadow-[var(--luxury-gold)]/20 group-hover:border-[var(--luxury-gold)]/60 transition-all duration-300`}>
                  <BookOpen className="w-5 h-5 sm:w-6 sm:h-6 md:w-7 md:h-7 text-[var(--luxury-gold)] drop-shadow-lg" />
                </div>
              </div>
            </div>
            <h1 className="text-2xl xs:text-3xl sm:text-4xl md:text-5xl font-serif font-semibold mb-2 sm:mb-3 tracking-tight leading-tight px-2">
              <span className={`${theme.theme_layout_mode === 'light' 
                ? 'bg-gradient-to-r from-gray-900 via-[var(--luxury-gold)] to-gray-900' 
                : 'bg-gradient-to-r from-white via-[var(--luxury-gold)] to-white'} bg-clip-text text-transparent`}>
                Our Blog
              </span>
            </h1>
            <div className="w-12 sm:w-16 md:w-20 h-0.5 bg-gradient-to-r from-transparent via-[var(--luxury-gold)] to-transparent mx-auto mb-2 sm:mb-3"></div>
            <p className={`text-sm sm:text-base md:text-lg ${textClasses.secondary} font-light leading-relaxed max-w-xl mx-auto tracking-wide px-2 sm:px-4`}>
              Discover stories, insights, and updates from our luxury hotel
            </p>
            <div className="mt-4 flex items-center justify-center gap-2 text-[var(--luxury-gold)]/60">
              <Sparkles className="w-4 h-4 animate-pulse" />
              <span className="text-xs sm:text-sm font-light tracking-wider uppercase">Premium Content</span>
              <Sparkles className="w-4 h-4 animate-pulse" style={{ animationDelay: '0.5s' }} />
            </div>
          </div>
        </div>
        <div className="absolute bottom-0 left-0 w-full h-px bg-gradient-to-r from-transparent via-[var(--luxury-gold)]/30 to-transparent"></div>
      </div>

      {/* Main Content - Full Width */}
      <div className="w-full py-12 sm:py-16 lg:py-20">
        <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">
        {/* Search Section */}
        <div className="mb-12 sm:mb-16">
          <div className="flex flex-col lg:flex-row gap-6 mb-8">
            <div className="flex-1 relative group">
              <div className="absolute inset-0 bg-gradient-to-r from-[var(--luxury-gold)]/10 to-transparent rounded-xl blur-xl opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
              <div className="relative">
                <Search className="absolute left-5 top-1/2 transform -translate-y-1/2 text-[var(--luxury-gold)] w-5 h-5 z-10" />
                <input
                  type="text"
                  placeholder="Search blog posts..."
                  value={searchTerm}
                  onChange={(e) => {
                    setSearchTerm(e.target.value);
                    setCurrentPage(1);
                  }}
                  className={`w-full pl-14 pr-5 py-4 ${inputClasses} border border-[var(--luxury-gold)]/20 rounded-xl placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-[var(--luxury-gold)]/50 focus:border-[var(--luxury-gold)]/50 transition-all duration-300 backdrop-blur-sm font-light`}
                />
              </div>
            </div>
          </div>
        </div>

        {/* Main Layout: Posts on Left, Tags on Right */}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-12">
          {/* Blog Posts Section */}
          <div className="lg:col-span-9">

            {/* Results Count */}
            {!loading && total > 0 && (
              <div className={`mb-8 ${textClasses.muted} font-light text-sm`}>
                Showing {posts.length} of {total} posts
              </div>
            )}

            {/* Blog Posts Grid - Luxury Design */}
            {posts.length === 0 ? (
              <div className="text-center py-20">
                <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-[var(--luxury-gold)]/10 mb-6">
                  <BookOpen className="w-10 h-10 text-[var(--luxury-gold)]" />
                </div>
                <p className={`${textClasses.muted} text-xl font-light`}>No blog posts found</p>
                <p className={`${textClasses.muted} text-sm mt-2`}>Try adjusting your search or filters</p>
              </div>
            ) : (
              <>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-8 lg:gap-10 mb-12">
                  {posts.map((post, index) => (
                    <Link
                      key={post.id}
                      to={`/blog/${post.slug}`}
                      className={`group relative ${cardClasses} rounded-3xl border-2 border-[var(--luxury-gold)]/20 overflow-hidden hover:border-[var(--luxury-gold)]/60 transition-all duration-700 hover:shadow-2xl hover:shadow-[var(--luxury-gold)]/30 hover:-translate-y-3`}
                      style={{ animationDelay: `${index * 50}ms` }}
                    >
                      {/* Premium Glow Effects */}
                      <div className="absolute inset-0 bg-gradient-to-br from-[var(--luxury-gold)]/0 via-[var(--luxury-gold)]/0 to-[var(--luxury-gold)]/0 group-hover:from-[var(--luxury-gold)]/10 group-hover:via-[var(--luxury-gold)]/5 group-hover:to-[var(--luxury-gold)]/10 transition-all duration-700 rounded-3xl blur-2xl opacity-0 group-hover:opacity-100"></div>
                      <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-transparent via-[var(--luxury-gold)]/50 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
                      
                      {/* Content */}
                      <div className="relative z-10">
                        {post.featured_image && (
                          <div className="relative h-72 sm:h-80 overflow-hidden">
                            <div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/40 to-transparent z-10"></div>
                            <img
                              src={post.featured_image}
                              alt={post.title}
                              className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-1000 ease-out"
                            />
                            {/* Premium Badge Overlay */}
                            <div className="absolute top-6 left-6 z-20">
                              <div className="bg-gradient-to-br from-[var(--luxury-gold)]/20 to-[var(--luxury-gold-dark)]/10 backdrop-blur-md rounded-2xl px-4 py-2 border border-[var(--luxury-gold)]/40 shadow-xl">
                                <div className="flex items-center gap-2 text-[var(--luxury-gold)]">
                                  <Eye className="w-4 h-4" />
                                  <span className="text-sm font-semibold">{post.views_count}</span>
                                </div>
                              </div>
                            </div>
                            {/* Luxury Corner Accent */}
                            <div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-[var(--luxury-gold)]/20 to-transparent rounded-bl-full opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
                          </div>
                        )}
                        <div className="p-8">
                          {post.tags && post.tags.length > 0 && (
                            <div className="flex flex-wrap gap-2 mb-5">
                              {post.tags.slice(0, 2).map((tag) => (
                                <span
                                  key={tag}
                                  className="inline-flex items-center gap-1.5 px-4 py-1.5 bg-gradient-to-br from-[var(--luxury-gold)]/15 to-[var(--luxury-gold)]/5 text-[var(--luxury-gold)] rounded-full text-xs font-semibold border border-[var(--luxury-gold)]/30 backdrop-blur-sm shadow-lg"
                                >
                                  <Tag className="w-3 h-3" />
                                  {tag}
                                </span>
                              ))}
                            </div>
                          )}
                          <h2 className={`text-2xl sm:text-3xl font-serif font-bold ${textClasses.primary} mb-4 group-hover:text-[var(--luxury-gold)] transition-colors duration-500 line-clamp-2 leading-tight tracking-tight`}>
                            {post.title}
                          </h2>
                          {post.excerpt && (
                            <p className={`${textClasses.secondary} text-base mb-6 line-clamp-3 font-light leading-relaxed`}>
                              {post.excerpt}
                            </p>
                          )}
                          <div className={`flex items-center justify-between text-sm ${textClasses.muted} pt-6 border-t border-[var(--luxury-gold)]/20 mb-6`}>
                            <div className="flex items-center gap-4">
                              {post.published_at && (
                                <div className="flex items-center gap-2">
                                  <Calendar className="w-4 h-4 text-[var(--luxury-gold)]" />
                                  <span className="font-light">{formatDate(post.published_at)}</span>
                                </div>
                              )}
                            </div>
                            {post.author_name && (
                              <div className="flex items-center gap-2">
                                <User className="w-4 h-4 text-[var(--luxury-gold)]" />
                                <span className="font-light">{post.author_name}</span>
                              </div>
                            )}
                          </div>
                          <div className="flex items-center justify-between pt-4 border-t border-[var(--luxury-gold)]/10">
                            <div className="flex items-center gap-3 text-[var(--luxury-gold)] group-hover:gap-4 transition-all duration-300">
                              <span className="text-sm font-semibold tracking-wide uppercase">Read Article</span>
                              <ArrowRight className="w-5 h-5 group-hover:translate-x-2 transition-transform duration-300" />
                            </div>
                            <div className="w-12 h-0.5 bg-gradient-to-r from-[var(--luxury-gold)] to-transparent group-hover:w-20 transition-all duration-500"></div>
                          </div>
                        </div>
                      </div>
                    </Link>
                  ))}
                </div>

                {/* Pagination */}
                {totalPages > 1 && (
                  <div className="mt-16 flex justify-center">
                    <Pagination
                      currentPage={currentPage}
                      totalPages={totalPages}
                      onPageChange={setCurrentPage}
                    />
                  </div>
                )}
              </>
            )}
          </div>

          {/* Tags Sidebar - Right Side */}
          <div className="lg:col-span-3">
            {allTags.length > 0 && (
              <div className="sticky top-8">
                <div className={`${cardClasses} rounded-3xl border-2 border-[var(--luxury-gold)]/20 p-8 backdrop-blur-xl shadow-2xl`}>
                  <div className="flex items-center gap-3 mb-6 pb-6 border-b border-[var(--luxury-gold)]/20">
                    <div className="w-1 h-8 bg-gradient-to-b from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] rounded-full"></div>
                    <h3 className={`text-xl font-serif font-bold ${textClasses.primary}`}>Filter by Tags</h3>
                  </div>
                  <div className="space-y-3">
                    <button
                      onClick={() => {
                        setSelectedTag(null);
                        setCurrentPage(1);
                      }}
                      className={`group relative w-full text-left px-5 py-4 rounded-2xl text-sm font-medium transition-all duration-300 overflow-hidden ${
                        selectedTag === null
                          ? 'bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] text-[#0f0f0f] shadow-lg shadow-[var(--luxury-gold)]/40'
                          : `${cardClasses} ${textClasses.secondary} border-2 border-[var(--luxury-gold)]/20 hover:border-[var(--luxury-gold)]/50 hover:text-[var(--luxury-gold)] ${theme.theme_layout_mode === 'light' ? 'hover:bg-gray-100' : 'hover:bg-[#1a1a1a]'}`
                      }`}
                    >
                      <span className="relative z-10 flex items-center gap-2">
                        <Tag className="w-4 h-4" />
                        All Posts
                      </span>
                      {selectedTag === null && (
                        <div className="absolute inset-0 bg-gradient-to-r from-white/20 to-transparent animate-shimmer"></div>
                      )}
                    </button>
                    {allTags.map((tag) => (
                      <button
                        key={tag}
                        onClick={() => {
                          setSelectedTag(tag);
                          setCurrentPage(1);
                        }}
                        className={`group relative w-full text-left px-5 py-4 rounded-2xl text-sm font-medium transition-all duration-300 overflow-hidden ${
                          selectedTag === tag
                            ? 'bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] text-[#0f0f0f] shadow-lg shadow-[var(--luxury-gold)]/40'
                            : `${cardClasses} ${textClasses.secondary} border-2 border-[var(--luxury-gold)]/20 hover:border-[var(--luxury-gold)]/50 hover:text-[var(--luxury-gold)] ${theme.theme_layout_mode === 'light' ? 'hover:bg-gray-100' : 'hover:bg-[#1a1a1a]'}`
                        }`}
                      >
                        <span className="relative z-10 flex items-center gap-2">
                          <Tag className="w-4 h-4" />
                          {tag}
                        </span>
                        {selectedTag === tag && (
                          <div className="absolute inset-0 bg-gradient-to-r from-white/20 to-transparent animate-shimmer"></div>
                        )}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
        </div>
      </div>
    </div>
  );
};

export default BlogPage;
