import { ArrowRight, BookOpen, Search } from 'lucide-react';

import { Head, Link, router, usePage } from '@inertiajs/react';

import { BlogCard } from '@/Components/marketing/BlogCard';
import { MarketingFooter } from '@/Components/marketing/MarketingFooter';
import { MarketingNav } from '@/Components/marketing/MarketingNav';
import { NewsletterSignup } from '@/Components/marketing/NewsletterSignup';
import InertiaPagination from '@/Components/Shared/InertiaPagination';
import { Button } from '@/Components/ui/button';
import { trackEvent } from '@/lib/analytics';
import { BLOG_CATEGORY_FILTER_CLICK } from '@/lib/event-catalog';
import { cn } from '@/lib/utils';
import { type PageProps } from '@/types';

interface BlogPost {
  id: number;
  title: string;
  slug: string;
  excerpt: string;
  author: string;
  published_at: string;
  category: string | null;
}

interface PaginatedResponse<T> {
  data: T[];
  current_page: number;
  last_page: number;
  per_page: number;
  total: number;
  links: Array<{ url: string | null; label: string; active: boolean }>;
}

interface BlogIndexProps {
  canLogin: boolean;
  canRegister: boolean;
  posts: PaginatedResponse<BlogPost>;
  categories: string[];
  activeCategory: string | null;
  currentSearch: string | null;
}

const categoryLabels: Record<string, string> = {
  'gsc-analytics': 'GSC & Analytics',
  'content-optimization': 'Content Optimization',
  'keyword-strategy': 'Keyword Strategy',
  'wordpress-seo': 'WordPress SEO',
  'seo-measurement': 'SEO Measurement',
};

type BlogIndexComponent = ((props: BlogIndexProps) => JSX.Element) & {
  disableGlobalUi?: boolean;
};

const BlogIndex: BlogIndexComponent = ({
  canLogin,
  canRegister,
  posts,
  categories,
  activeCategory,
  currentSearch,
}) => {
  const appName = import.meta.env.VITE_APP_NAME || 'RankWiz';
  const { app_url } = usePage<PageProps>().props;

  const buildPaginatedUrl = (page: number) => {
    const params = new URLSearchParams();
    if (page > 1) params.set('page', String(page));
    if (activeCategory) params.set('category', activeCategory);
    if (currentSearch) params.set('search', currentSearch);
    const qs = params.toString();
    return `${app_url}/blog${qs ? `?${qs}` : ''}`;
  };

  const handleCategoryFilter = (category: string | null) => {
    if (category) {
      trackEvent(BLOG_CATEGORY_FILTER_CLICK, { category });
    }
    const params: Record<string, string> = {};
    if (category) params.category = category;
    if (currentSearch) params.search = currentSearch;
    router.get(route('blog.index'), params, { preserveScroll: true });
  };

  const handleSearch = (value: string) => {
    const params: Record<string, string> = {};
    if (value) params.search = value;
    if (activeCategory) params.category = activeCategory;
    router.get(route('blog.index'), params, { preserveState: true, replace: true });
  };

  return (
    <>
      <Head
        title={
          activeCategory ? `${categoryLabels[activeCategory] || activeCategory} — Blog` : 'Blog'
        }
      >
        <link rel="canonical" href={buildPaginatedUrl(posts.current_page)} />
        {(activeCategory || currentSearch || posts.current_page > 1) && (
          <meta name="robots" content="noindex, follow" />
        )}
        <link
          rel="alternate"
          type="application/rss+xml"
          title="RankWiz Blog RSS Feed"
          href="/blog/feed.xml"
        />
        <link
          rel="alternate"
          type="application/atom+xml"
          title="RankWiz Blog Atom Feed"
          href="/blog/feed.atom"
        />
        {posts.current_page < posts.last_page && (
          <link rel="next" href={buildPaginatedUrl(posts.current_page + 1)} />
        )}
        {posts.current_page > 1 && (
          <link rel="prev" href={buildPaginatedUrl(posts.current_page - 1)} />
        )}
        <meta
          name="description"
          content="SEO insights, WordPress optimization tips, and content strategy guides. Learn how to improve your search rankings with data-driven SEO techniques."
        />
        <meta property="og:title" content={`Blog — ${appName}`} />
        <meta
          property="og:description"
          content="SEO insights, WordPress optimization tips, and content strategy guides from the RankWiz team."
        />
        <meta property="og:type" content="website" />
        <meta property="og:url" content={`${app_url}/blog`} />
        <meta property="og:image" content={`${app_url}/og-image.png`} />
        <meta
          property="og:image:alt"
          content={`${appName} Blog — SEO Insights and WordPress Tips`}
        />
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:site" content="@rankwiz_ai" />
        <meta name="twitter:title" content={`Blog — ${appName}`} />
        <meta
          name="twitter:description"
          content="SEO insights and WordPress optimization tips from the RankWiz team."
        />
        <meta name="twitter:image" content={`${app_url}/og-image.png`} />
        <meta name="twitter:image:width" content="1200" />
        <meta name="twitter:image:height" content="630" />
        <meta property="og:image:width" content="1200" />
        <meta property="og:image:height" content="630" />
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'Blog',
            name: `${appName} Blog`,
            description: 'SEO insights, WordPress optimization tips, and content strategy guides.',
            url: `${app_url}/blog`,
            publisher: {
              '@type': 'Organization',
              name: appName,
            },
          })}
        </script>
        {posts.data.length > 0 && (
          <script type="application/ld+json">
            {JSON.stringify({
              '@context': 'https://schema.org',
              '@type': 'CollectionPage',
              name: `${appName} Blog`,
              url: `${app_url}/blog`,
              mainEntity: {
                '@type': 'ItemList',
                itemListElement: posts.data.map((p, i) => ({
                  '@type': 'ListItem',
                  position: i + 1,
                  url: `${app_url}/blog/${p.slug}`,
                  name: p.title,
                })),
              },
            })}
          </script>
        )}
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'BreadcrumbList',
            itemListElement: [
              {
                '@type': 'ListItem',
                position: 1,
                name: 'Home',
                item: `${app_url}/`,
              },
              {
                '@type': 'ListItem',
                position: 2,
                name: 'Blog',
                item: `${app_url}/blog`,
              },
              ...(activeCategory
                ? [
                    {
                      '@type': 'ListItem',
                      position: 3,
                      name: categoryLabels[activeCategory] || activeCategory,
                      item: `${app_url}/blog?category=${encodeURIComponent(activeCategory)}`,
                    },
                  ]
                : []),
            ],
          })}
        </script>
      </Head>

      <div className="min-h-screen bg-gradient-to-b from-background to-muted/30">
        <MarketingNav canLogin={canLogin} canRegister={canRegister} />

        <main id="main-content">
          {/* Hero Section */}
          <section className="container py-16 text-center">
            <div className="mx-auto max-w-3xl space-y-6">
              <div className="animate-fade-in-up inline-flex items-center gap-2 rounded-full border bg-muted px-4 py-1.5 text-sm text-muted-foreground">
                <BookOpen className="h-4 w-4" aria-hidden="true" />
                SEO Insights & WordPress Tips
              </div>
              <h1 className="animate-fade-in-up animate-delay-100 text-4xl font-bold tracking-tight sm:text-5xl md:text-6xl">
                {appName} Blog
                <br />
                <span className="text-primary">Data-Driven SEO Strategies</span>
              </h1>
              <p className="animate-fade-in-up animate-delay-200 text-lg text-muted-foreground md:text-xl">
                Learn how to analyze your traffic, optimize your content, and grow your WordPress
                site with actionable SEO insights.
              </p>
            </div>
          </section>

          {/* Search */}
          <section className="container pb-4">
            <div className="mx-auto max-w-md">
              <div className="relative">
                <Search
                  className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"
                  aria-hidden="true"
                />
                <input
                  type="search"
                  placeholder="Search articles..."
                  defaultValue={currentSearch ?? ''}
                  onChange={(e) => handleSearch(e.target.value)}
                  aria-label="Search blog posts"
                  className="w-full rounded-lg border border-border bg-background py-2 pl-10 pr-4 text-sm placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
            </div>
          </section>

          {/* Category Filter */}
          {categories.length > 0 && (
            <section className="container pb-8">
              <nav
                aria-label="Blog categories"
                className="flex flex-wrap items-center justify-center gap-2"
              >
                <button
                  onClick={() => handleCategoryFilter(null)}
                  className={cn(
                    'rounded-full border px-4 py-1.5 text-sm font-medium transition-colors',
                    activeCategory === null
                      ? 'border-primary bg-primary text-primary-foreground'
                      : 'border-border bg-background text-muted-foreground hover:border-primary hover:text-foreground',
                  )}
                >
                  All
                </button>
                {categories.map((category) => (
                  <button
                    key={category}
                    onClick={() => handleCategoryFilter(category)}
                    className={cn(
                      'rounded-full border px-4 py-1.5 text-sm font-medium transition-colors',
                      activeCategory === category
                        ? 'border-primary bg-primary text-primary-foreground'
                        : 'border-border bg-background text-muted-foreground hover:border-primary hover:text-foreground',
                    )}
                  >
                    {categoryLabels[category] || category}
                  </button>
                ))}
              </nav>
            </section>
          )}

          {/* Blog Posts Grid */}
          <section className="container py-8">
            {posts.data.length > 0 ? (
              <>
                <div className="grid gap-8 md:grid-cols-2 lg:grid-cols-3">
                  {posts.data.map((post) => (
                    <BlogCard
                      key={post.id}
                      title={post.title}
                      slug={post.slug}
                      excerpt={post.excerpt}
                      author={post.author}
                      publishedAt={post.published_at}
                    />
                  ))}
                </div>
                {posts.last_page > 1 && (
                  <div className="mt-12 flex justify-center">
                    <InertiaPagination
                      links={posts.links}
                      currentPage={posts.current_page}
                      lastPage={posts.last_page}
                      perPage={posts.per_page}
                      total={posts.total}
                    />
                  </div>
                )}
              </>
            ) : (
              <div className="mx-auto max-w-2xl rounded-lg border bg-card p-12 text-center">
                <BookOpen
                  className="mx-auto mb-4 h-12 w-12 text-muted-foreground"
                  aria-hidden="true"
                />
                <h2 className="mb-2 text-xl font-semibold">
                  {currentSearch
                    ? 'No results found'
                    : activeCategory
                      ? 'No posts in this category'
                      : 'Blog Coming Soon'}
                </h2>
                <p className="text-muted-foreground">
                  {currentSearch ? (
                    <>
                      No articles match &ldquo;{currentSearch}&rdquo;.{' '}
                      <button
                        onClick={() => handleSearch('')}
                        className="font-medium text-primary hover:underline"
                      >
                        Clear search
                      </button>
                    </>
                  ) : activeCategory ? (
                    <>
                      No articles found for this category.{' '}
                      <button
                        onClick={() => handleCategoryFilter(null)}
                        className="font-medium text-primary hover:underline"
                      >
                        View all posts
                      </button>
                    </>
                  ) : (
                    "We're writing our first posts on WordPress SEO, traffic analysis, and content optimization. Check back soon."
                  )}
                </p>
              </div>
            )}
          </section>

          {/* Newsletter Signup */}
          {posts.data.length > 0 && (
            <section className="container py-12">
              <div className="mx-auto max-w-md">
                <NewsletterSignup />
              </div>
            </section>
          )}

          {/* CTA Section */}
          <section className="container py-24">
            <div className="rounded-2xl bg-gradient-to-r from-primary/10 via-primary/5 to-background p-6 text-center sm:p-12">
              <h2 className="mb-4 text-2xl font-bold tracking-tight sm:text-3xl">
                Ready to Optimize Your WordPress Site?
              </h2>
              <p className="mb-8 text-base text-muted-foreground sm:text-lg">
                Connect your Google Search Console and start analyzing your traffic in minutes.
              </p>
              <div className="flex flex-wrap items-center justify-center gap-4">
                {canRegister && (
                  <Button size="lg" asChild>
                    <Link href={route('register')}>
                      Start Free Analysis
                      <ArrowRight className="ml-2 h-4 w-4" aria-hidden="true" />
                    </Link>
                  </Button>
                )}
                <Button size="lg" variant="outline" asChild>
                  <Link href={route('welcome')}>Learn More</Link>
                </Button>
              </div>
            </div>
          </section>
        </main>

        <MarketingFooter />
      </div>
    </>
  );
};

BlogIndex.disableGlobalUi = true;

export default BlogIndex;
