import { ArrowLeft, ArrowRight, BookOpen, Calendar, Clock } from 'lucide-react';

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

import { MarketingFooter } from '@/Components/marketing/MarketingFooter';
import { MarketingNav } from '@/Components/marketing/MarketingNav';
import { Button } from '@/Components/ui/button';
import { CTA_LABELS } from '@/config/cta-labels';
import { trackEvent } from '@/lib/analytics';
import {
  HUB_CTA_CLICKED,
  HUB_FEATURE_LINK_CLICKED,
  HUB_POST_CLICKED,
  HUB_RELATED_GUIDE_CLICKED,
} from '@/lib/event-catalog';
import { formatDateOnly } from '@/lib/format';
import { type PageProps } from '@/types';

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

interface RelatedHub {
  slug: string;
  title: string;
  description: string;
}

interface HubProps {
  can_login: boolean;
  can_register: boolean;
  slug: string;
  hub_title: string;
  hub_heading: string;
  hub_description: string;
  category: string;
  feature_anchor: string;
  feature_label: string;
  feature_cta: string;
  posts: HubPost[];
  related_hubs: RelatedHub[];
}

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

const Hub: HubComponent = ({
  can_login,
  can_register,
  slug,
  hub_heading,
  hub_description,
  feature_anchor,
  feature_cta,
  posts,
  related_hubs,
}) => {
  const appName = import.meta.env.VITE_APP_NAME || 'RankWiz';
  const { app_url } = usePage<PageProps>().props;

  const breadcrumbSchema = {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: [
      { '@type': 'ListItem', position: 1, name: 'Home', item: `${app_url}/` },
      { '@type': 'ListItem', position: 2, name: 'Learn', item: `${app_url}/learn` },
      { '@type': 'ListItem', position: 3, name: hub_heading, item: `${app_url}/learn/${slug}` },
    ],
  };

  const featureUrl = `/features#${feature_anchor}`;

  return (
    <>
      <Head title={`${hub_heading} — ${appName}`}>
        <link rel="canonical" href={`${app_url}/learn/${slug}`} />
        <meta name="description" content={hub_description} />
        <meta property="og:title" content={`${hub_heading} — ${appName}`} />
        <meta property="og:description" content={hub_description} />
        <meta property="og:type" content="website" />
        <meta property="og:url" content={`${app_url}/learn/${slug}`} />
        <meta property="og:image" content={`${app_url}/og-image.png`} />
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:title" content={`${hub_heading} — ${appName}`} />
        <meta name="twitter:description" content={hub_description} />
        <script type="application/ld+json">{JSON.stringify(breadcrumbSchema)}</script>
      </Head>

      <div className="min-h-screen bg-background">
        <MarketingNav canLogin={can_login} canRegister={can_register} />

        <main id="main-content">
          {/* Back nav */}
          <div className="container py-6">
            <Link
              href="/blog"
              className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
            >
              <ArrowLeft className="h-4 w-4" aria-hidden="true" />
              All guides
            </Link>
          </div>

          {/* Hero */}
          <section className="container pb-16 pt-4 text-center">
            <div className="mx-auto max-w-3xl">
              <div className="mb-4 inline-flex items-center gap-2 rounded-full border border-primary/30 bg-primary/5 px-4 py-2 text-xs font-semibold text-primary">
                <BookOpen className="h-3.5 w-3.5" aria-hidden="true" />
                Complete Guide
              </div>
              <h1 className="mb-6 text-3xl font-extrabold tracking-tight text-foreground sm:text-4xl lg:text-5xl">
                {hub_heading}
              </h1>
              <p className="mb-8 mx-auto max-w-2xl text-lg text-muted-foreground">
                {hub_description}
              </p>
              {can_register && (
                <Button size="lg" asChild>
                  <Link
                    href="/register"
                    onClick={() => trackEvent(HUB_CTA_CLICKED, { hub: slug, location: 'hero' })}
                  >
                    {CTA_LABELS.FREE_ENTRY}
                    <ArrowRight className="ml-2 h-4 w-4" aria-hidden="true" />
                  </Link>
                </Button>
              )}
            </div>
          </section>

          {/* Product feature CTA */}
          <section className="container pb-16">
            <div className="mx-auto max-w-4xl rounded-xl border bg-primary/5 p-6 text-center">
              <p className="mb-3 text-sm font-semibold text-foreground">{feature_cta}</p>
              <Link
                href={featureUrl}
                className="inline-flex items-center gap-1.5 text-sm text-primary underline-offset-4 hover:underline"
                onClick={() =>
                  trackEvent(HUB_FEATURE_LINK_CLICKED, { hub: slug, anchor: feature_anchor })
                }
              >
                Explore the feature
                <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
              </Link>
            </div>
          </section>

          {/* Posts grid */}
          <section className="container pb-24">
            <div className="mx-auto max-w-4xl">
              <h2 className="mb-8 text-2xl font-bold tracking-tight text-foreground">
                Articles in this guide
                {posts.length > 0 && (
                  <span className="ml-2 text-base font-normal text-muted-foreground">
                    ({posts.length})
                  </span>
                )}
              </h2>

              {posts.length === 0 ? (
                <p className="text-muted-foreground">
                  Articles are coming soon. Check back shortly.
                </p>
              ) : (
                <div className="grid gap-6 sm:grid-cols-2">
                  {posts.map((post) => (
                    <Link
                      key={post.id}
                      href={`/blog/${post.slug}`}
                      className="group flex flex-col rounded-xl border bg-card p-6 transition-shadow hover:shadow-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                      onClick={() => trackEvent(HUB_POST_CLICKED, { hub: slug, post: post.slug })}
                    >
                      <h3 className="mb-2 flex-1 text-base font-semibold text-foreground group-hover:text-primary transition-colors">
                        {post.title ?? ''}
                      </h3>
                      <p className="mb-4 line-clamp-2 text-sm text-muted-foreground">
                        {post.excerpt ?? ''}
                      </p>
                      <div className="flex items-center gap-4 text-xs text-muted-foreground">
                        <span className="flex items-center gap-1">
                          <Calendar className="h-3 w-3" aria-hidden="true" />
                          {formatDateOnly(post.published_at)}
                        </span>
                        {post.reading_time_minutes && (
                          <span className="flex items-center gap-1">
                            <Clock className="h-3 w-3" aria-hidden="true" />
                            {post.reading_time_minutes} min
                          </span>
                        )}
                      </div>
                    </Link>
                  ))}
                </div>
              )}
            </div>
          </section>

          {/* Related Guides */}
          {related_hubs.length > 0 && (
            <section className="container pb-16">
              <div className="mx-auto max-w-4xl">
                <h2 className="mb-6 text-xl font-bold tracking-tight text-foreground">
                  Related Guides
                </h2>
                <div className="grid gap-4 sm:grid-cols-2">
                  {related_hubs.map((hub) => (
                    <Link
                      key={hub.slug}
                      href={`/learn/${hub.slug}`}
                      className="group flex flex-col rounded-xl border bg-card p-5 transition-shadow hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                      onClick={() =>
                        trackEvent(HUB_RELATED_GUIDE_CLICKED, {
                          from_hub: slug,
                          to_hub: hub.slug,
                        })
                      }
                    >
                      <h3 className="mb-1.5 font-semibold text-foreground group-hover:text-primary transition-colors">
                        {hub.title}
                      </h3>
                      <p className="line-clamp-2 text-sm text-muted-foreground">
                        {hub.description}
                      </p>
                    </Link>
                  ))}
                </div>
              </div>
            </section>
          )}

          {/* Bottom CTA */}
          {can_register && (
            <section className="container pb-24">
              <div className="mx-auto max-w-2xl rounded-2xl bg-primary/5 p-12 text-center">
                <h2 className="mb-4 text-2xl font-bold text-foreground">
                  Apply These Strategies to Your Site
                </h2>
                <p className="mb-6 text-muted-foreground">
                  Connect Google Search Console and get AI-powered recommendations in 2 minutes.
                  Free to start.
                </p>
                <Button size="lg" asChild>
                  <Link
                    href="/register"
                    onClick={() => trackEvent(HUB_CTA_CLICKED, { hub: slug, location: 'bottom' })}
                  >
                    {CTA_LABELS.FREE_ENTRY}
                    <ArrowRight className="ml-2 h-4 w-4" aria-hidden="true" />
                  </Link>
                </Button>
              </div>
            </section>
          )}
        </main>

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

Hub.disableGlobalUi = true;

export default Hub;
