import { useState, useEffect } from "react";
import { useSearchParams } from "react-router-dom";
import { BlogHeader } from "@/components/BlogHeader";
import { BlogFooter } from "@/components/BlogFooter";
import { PromoBanner } from "@/components/PromoBanner";
import { CategoryNav, type CoachingCategory } from "@/components/CategoryNav";
import { BlogCard } from "@/components/BlogCard";
import { SEOHead } from "@/components/SEOHead";
import { TrendingArticles } from "@/components/TrendingArticles";
import { supabase } from "@/integrations/supabase/client";
import type { BlogPost } from "@/components/BlogCard";

/** Truncated page list: first, last, current ± siblings, with ellipses. */
function getVisiblePages(current: number, total: number, siblingCount = 1): (number | "ellipsis")[] {
  const maxVisible = siblingCount * 2 + 5; // first + last + current + siblings + up to 2 ellipses
  if (total <= maxVisible) {
    return Array.from({ length: total }, (_, i) => i + 1);
  }

  const leftSibling = Math.max(current - siblingCount, 1);
  const rightSibling = Math.min(current + siblingCount, total);
  const showLeftEllipsis = leftSibling > 2;
  const showRightEllipsis = rightSibling < total - 1;

  if (!showLeftEllipsis && showRightEllipsis) {
    const leftCount = 3 + 2 * siblingCount;
    return [
      ...Array.from({ length: leftCount }, (_, i) => i + 1),
      "ellipsis",
      total,
    ];
  }

  if (showLeftEllipsis && !showRightEllipsis) {
    const rightCount = 3 + 2 * siblingCount;
    return [
      1,
      "ellipsis",
      ...Array.from({ length: rightCount }, (_, i) => total - rightCount + 1 + i),
    ];
  }

  return [
    1,
    "ellipsis",
    ...Array.from({ length: rightSibling - leftSibling + 1 }, (_, i) => leftSibling + i),
    "ellipsis",
    total,
  ];
}

const categoryLabels: Record<string, string> = {
  "all": "All Coaching Topics",
  "life-coaching": "Life Coaching",
  "corporate-coaching": "Corporate Coaching",
  "business-coaching": "Business Coaching",
  "adhd-coaching": "ADHD Coaching",
  "executive-leadership-coaching": "Executive & Leadership Coaching",
  "health-wellness-coaching": "Health & Wellness Coaching",
  "spirituality-coaching": "Spirituality Coaching",
  "retirement-coaching": "Retirement Coaching",
  "recovery-coaching": "Recovery Coaching",
  "relationship-coaching": "Relationship Coaching",
};

const categoryDescriptions: Record<string, string> = {
  "all": "Discover expert coaching insights, strategies, and tips from professional coaches across all coaching specialties including life, business, executive, and wellness coaching.",
  "life-coaching": "Expert life coaching insights, strategies, and advice from professional life coaches to help you achieve personal growth and reach your full potential.",
  "corporate-coaching": "Professional corporate coaching tips and strategies to improve workplace performance, leadership skills, and organizational success.",
  "business-coaching": "Business coaching insights from expert coaches to help entrepreneurs and business leaders scale their companies and achieve sustainable growth.",
  "adhd-coaching": "ADHD coaching strategies and techniques from specialists to help improve focus, productivity, and daily life management.",
  "executive-leadership-coaching": "Executive and leadership coaching insights for C-suite professionals and senior leaders to enhance strategic thinking and team performance.",
  "health-wellness-coaching": "Health and wellness coaching tips from certified coaches to help you achieve optimal physical and mental wellbeing.",
  "spirituality-coaching": "Spiritual coaching guidance and insights to help you connect with your inner self and find deeper meaning in life.",
  "retirement-coaching": "Retirement coaching advice to help you plan and navigate a fulfilling post-career life with purpose and joy.",
  "recovery-coaching": "Recovery coaching support and strategies for individuals in recovery, offering guidance to maintain sobriety and build a fulfilling life.",
  "relationship-coaching": "Relationship coaching insights and strategies to help you build healthier connections, improve communication, and strengthen your relationships.",
};

const POSTS_PER_PAGE = 12;

const BlogHome = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const categoryParam = searchParams.get("category") as CoachingCategory | null;
  const pageParam = parseInt(searchParams.get("page") || "1", 10);
  const [activeCategory, setActiveCategory] = useState<CoachingCategory>(categoryParam || "all");
  const [currentPage, setCurrentPage] = useState<number>(pageParam);
  const [allPosts, setAllPosts] = useState<BlogPost[]>([]);
  const [filteredPosts, setFilteredPosts] = useState<BlogPost[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (categoryParam && categoryParam !== activeCategory) {
      setActiveCategory(categoryParam);
    }
    if (pageParam !== currentPage) {
      setCurrentPage(pageParam);
    }
  }, [categoryParam, pageParam]);

  useEffect(() => {
    const fetchPosts = async () => {
      setLoading(true);
      const { data, error } = await supabase
        .from("blog_posts")
        .select("id, title, slug, excerpt, content, category, author_name, author_avatar, author_profile_url, publish_date, updated_at, read_time, image, views, meta_title, meta_description, faq_schema")
        .eq("is_published", true)
        .order("publish_date", { ascending: false });

      if (error) {
        console.error("Error fetching posts:", error);
      } else if (data) {
        // Transform database posts to BlogPost format
        const posts: BlogPost[] = data.map((post: any) => ({
          id: post.id,
          title: post.title,
          slug: post.slug,
          excerpt: post.excerpt,
          content: post.content,
          category: post.category,
          author: {
            name: post.author_name,
            avatar: post.author_avatar,
            profileUrl: post.author_profile_url,
          },
          publishDate: new Date(post.publish_date).toLocaleDateString("en-US", {
            year: "numeric",
            month: "long",
            day: "numeric",
          }),
          readTime: post.read_time,
          image: post.image,
          views: post.views,
          updatedAt: post.updated_at,
        }));
        setAllPosts(posts);
        setFilteredPosts(posts);
      }
      setLoading(false);
    };

    fetchPosts();
  }, []);

  useEffect(() => {
    if (activeCategory === "all") {
      setFilteredPosts(allPosts);
    } else {
      setFilteredPosts(allPosts.filter((post) => post.category === activeCategory));
    }
    // Reset to page 1 when category changes
    setCurrentPage(1);
    setSearchParams(
      activeCategory === "all" 
        ? {} 
        : { category: activeCategory }
    );
  }, [activeCategory, allPosts]);

  // Pagination calculations
  const totalPages = Math.ceil(filteredPosts.length / POSTS_PER_PAGE);
  const startIndex = (currentPage - 1) * POSTS_PER_PAGE;
  const endIndex = startIndex + POSTS_PER_PAGE;
  const paginatedPosts = filteredPosts.slice(startIndex, endIndex);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    const params: Record<string, string> = { page: page.toString() };
    if (activeCategory !== "all") {
      params.category = activeCategory;
    }
    setSearchParams(params);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const featuredPost = currentPage === 1 ? paginatedPosts[0] : null;
  const regularPosts = currentPage === 1 ? paginatedPosts.slice(1) : paginatedPosts;

  // SEO configuration
  const pageTitle = activeCategory === "all" 
    ? "Coaching Conversations by Noomii - Expert Insights on Life, Business & Leadership Coaching"
    : `${categoryLabels[activeCategory]} - Expert Coaching Insights | Noomii`;
  
  const pageDescription = categoryDescriptions[activeCategory];
  
  let canonicalUrl = "https://blog.noomii.com/";
  if (activeCategory !== "all") {
    canonicalUrl += `?category=${activeCategory}`;
  }
  if (currentPage > 1) {
    canonicalUrl += activeCategory !== "all" ? `&page=${currentPage}` : `?page=${currentPage}`;
  }

  // Pagination meta tags
  const prevPage = currentPage > 1 ? currentPage - 1 : null;
  const nextPage = currentPage < totalPages ? currentPage + 1 : null;

  const visiblePages = getVisiblePages(currentPage, totalPages);

  // Organization + WebSite JSON-LD live once in index.html to avoid duplicates.
  const breadcrumbData = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: activeCategory === "all" 
      ? [
          {
            "@type": "ListItem",
            position: 1,
            name: "Home",
            item: "https://blog.noomii.com"
          }
        ]
      : [
          {
            "@type": "ListItem",
            position: 1,
            name: "Home",
            item: "https://blog.noomii.com"
          },
          {
            "@type": "ListItem",
            position: 2,
            name: categoryLabels[activeCategory],
            item: canonicalUrl
          }
        ]
  };

  // Enhanced Blog Collection Schema
  const blogListingData = filteredPosts.length > 0 ? {
    "@context": "https://schema.org",
    "@type": "Blog",
    name: pageTitle,
    description: pageDescription,
    url: canonicalUrl,
    inLanguage: "en-US",
    publisher: {
      "@type": "Organization",
      name: "Noomii",
      url: "https://www.noomii.com",
      logo: {
        "@type": "ImageObject",
        url: "https://blog.noomii.com/noomii-logo.png",
      },
    },
    blogPost: paginatedPosts.map((post) => ({
      "@type": "BlogPosting",
      headline: post.title,
      abstract: post.excerpt,
      url: `https://blog.noomii.com/blog/${post.slug}`,
      image: {
        "@type": "ImageObject",
        url: post.image,
      },
      datePublished: new Date(post.publishDate).toISOString(),
      dateModified: post.updatedAt ? new Date(post.updatedAt).toISOString() : new Date(post.publishDate).toISOString(),
      author: {
        "@type": "Person",
        name: post.author.name,
        url: post.author.profileUrl || "",
      },
      publisher: {
        "@type": "Organization",
        name: "Noomii",
      },
    })),
  } : null;

  // ItemList Schema for Article Listing (enhances search visibility)
  const itemListData = paginatedPosts.length > 0 ? {
    "@context": "https://schema.org",
    "@type": "ItemList",
    name: pageTitle,
    description: pageDescription,
    url: canonicalUrl,
    numberOfItems: paginatedPosts.length,
    itemListElement: paginatedPosts.map((post, index) => ({
      "@type": "ListItem",
      position: index + 1,
      item: {
        "@type": "Article",
        "@id": `https://blog.noomii.com/blog/${post.slug}`,
        headline: post.title,
        description: post.excerpt,
        image: {
          "@type": "ImageObject",
          url: post.image,
          width: 1200,
          height: 630,
        },
        datePublished: new Date(post.publishDate).toISOString(),
        dateModified: post.updatedAt ? new Date(post.updatedAt).toISOString() : new Date(post.publishDate).toISOString(),
        author: {
          "@type": "Person",
          name: post.author.name,
          url: post.author.profileUrl || "https://blog.noomii.com",
        },
        publisher: {
          "@type": "Organization",
          name: "Noomii",
          url: "https://www.noomii.com",
          logo: {
            "@type": "ImageObject",
            url: "https://blog.noomii.com/noomii-logo.png",
          },
        },
        mainEntityOfPage: {
          "@type": "WebPage",
          "@id": `https://blog.noomii.com/blog/${post.slug}`,
        },
        articleSection: categoryLabels[post.category as CoachingCategory] || post.category,
      },
    })),
  } : null;

  const structuredData: any[] = [breadcrumbData];
  if (blogListingData) {
    structuredData.push(blogListingData);
  }
  if (itemListData) {
    structuredData.push(itemListData);
  }

  return (
    <>
      <SEOHead
        title={pageTitle}
        description={pageDescription}
        canonical={canonicalUrl}
        ogType="website"
        keywords={[
          categoryLabels[activeCategory],
          "coaching",
          "professional development",
          "life coaching",
          "business coaching",
          "executive coaching",
          "wellness coaching",
          "coaching tips",
          "coaching strategies"
        ]}
        structuredData={structuredData}
        prevPage={prevPage ? `${canonicalUrl.split('?')[0]}${activeCategory !== "all" ? `?category=${activeCategory}&page=${prevPage}` : `?page=${prevPage}`}` : undefined}
        nextPage={nextPage ? `${canonicalUrl.split('?')[0]}${activeCategory !== "all" ? `?category=${activeCategory}&page=${nextPage}` : `?page=${nextPage}`}` : undefined}
      />
      
      <div className="min-h-screen bg-background">
        <BlogHeader />
        
        {/* Breadcrumb Navigation */}
        {activeCategory !== "all" && (
          <nav className="container mx-auto px-4 py-4 bg-muted/30" aria-label="Breadcrumb">
            <ol className="flex items-center gap-2 text-sm">
              <li>
                <a href="/" className="text-muted-foreground hover:text-primary transition-colors font-medium">
                  Home
                </a>
              </li>
              <li aria-hidden="true">
                <span className="text-muted-foreground">/</span>
              </li>
              <li>
                <span className="text-foreground font-medium">
                  {categoryLabels[activeCategory]}
                </span>
              </li>
            </ol>
          </nav>
        )}
        <CategoryNav activeCategory={activeCategory} onCategoryChange={setActiveCategory} />

        {/* Promotional Banner */}
        <div className="container mx-auto px-4 pt-4">
          <PromoBanner category={activeCategory !== "all" ? activeCategory : undefined} />
        </div>

        <main className="container mx-auto px-4 py-8">
          <div className="flex flex-col lg:flex-row gap-8">
            {/* Main Content */}
            <div className="flex-1 min-w-0">
              {/* Hero Section */}
              <section className="mb-12">
                <header className="text-center mb-8">
                  <h1 className="text-4xl md:text-5xl font-bold mb-4">
                    {activeCategory === "all" 
                      ? "Coaching Conversations by Noomii"
                      : `${categoryLabels[activeCategory]} Insights`
                    }
                  </h1>
                  <p className="text-xl text-muted-foreground max-w-3xl mx-auto">
                    {pageDescription}
                  </p>
                </header>

                {loading ? (
                  <div className="text-center py-12">
                    <p className="text-muted-foreground">Loading posts...</p>
                  </div>
                ) : featuredPost ? (
                  <div className="mb-8">
                    <BlogCard post={featuredPost} featured />
                  </div>
                ) : (
                  <div className="text-center py-12">
                    <p className="text-muted-foreground">No posts available yet.</p>
                  </div>
                )}
              </section>

              {/* Recent Articles */}
              {!loading && regularPosts.length > 0 && (
                <section>
                  <h2 className="text-2xl font-bold mb-6">
                    {activeCategory === "all"
                      ? "Recent Articles"
                      : `Recent ${categoryLabels[activeCategory]} Articles`}
                  </h2>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 gap-6">
                    {regularPosts.map((post) => (
                      <BlogCard key={post.id} post={post} />
                    ))}
                  </div>

                  {/* Pagination Controls */}
                  {totalPages > 1 && (
                    <nav
                      className="mt-12 flex flex-wrap justify-center items-center gap-1 sm:gap-2 max-w-full overflow-x-auto"
                      aria-label="Pagination"
                    >
                      <button
                        onClick={() => handlePageChange(currentPage - 1)}
                        disabled={currentPage === 1}
                        className="px-2.5 sm:px-4 py-2 rounded border border-border disabled:opacity-50 disabled:cursor-not-allowed hover:bg-muted transition-colors text-sm shrink-0"
                        aria-label="Previous page"
                      >
                        <span className="hidden sm:inline">Previous</span>
                        <span className="sm:hidden">Prev</span>
                      </button>

                      <div className="flex flex-wrap justify-center gap-1">
                        {visiblePages.map((page, index) =>
                          page === "ellipsis" ? (
                            <span
                              key={`ellipsis-${index}`}
                              className="px-2 py-2 text-muted-foreground select-none"
                              aria-hidden
                            >
                              …
                            </span>
                          ) : (
                            <button
                              key={page}
                              onClick={() => handlePageChange(page)}
                              className={`min-w-9 px-2.5 sm:px-3 py-2 rounded border transition-colors text-sm ${
                                page === currentPage
                                  ? "bg-primary text-primary-foreground border-primary"
                                  : "border-border hover:bg-muted"
                              }`}
                              aria-label={`Page ${page}`}
                              aria-current={page === currentPage ? "page" : undefined}
                            >
                              {page}
                            </button>
                          )
                        )}
                      </div>

                      <button
                        onClick={() => handlePageChange(currentPage + 1)}
                        disabled={currentPage === totalPages}
                        className="px-2.5 sm:px-4 py-2 rounded border border-border disabled:opacity-50 disabled:cursor-not-allowed hover:bg-muted transition-colors text-sm shrink-0"
                        aria-label="Next page"
                      >
                        Next
                      </button>
                    </nav>
                  )}
                </section>
              )}
            </div>

            {/* Trending Sidebar */}
            <aside className="lg:w-80 flex-shrink-0">
              <TrendingArticles />
            </aside>
          </div>
        </main>

        <BlogFooter />
      </div>
    </>
  );
};

export default BlogHome;
