'use client'

import Image from 'next/image'
import { useMemo, useState } from 'react'
import { useTranslations } from 'next-intl'
import { ArrowRight, ArrowUpRight, Calendar, Clock, User } from 'lucide-react'
import { PageHero } from '@/components/page-hero'
import { DataStates } from '@/components/api/data-states'
import { InfiniteScrollSentinel } from '@/components/api/infinite-scroll-sentinel'
import { Link } from '@/i18n/navigation'
import { useFetchData } from '@/hooks/api'
import type { BlogPost } from '@/lib/api/entities'
import { resolveAssetPath } from '@/lib/asset-paths'
import { useSiteData } from '@/contexts/site-data-context'
import { cn, formatDate } from '@/lib/utils'

function BlogPostCard({
  post,
  featured = false,
}: {
  post: BlogPost
  featured?: boolean
}) {
  const t = useTranslations('updates.blog')
  const href = post.slug ? `/blog/${post.slug}` : '/blog'

  return (
    <Link
      href={href}
      className={cn(
        'group flex h-full flex-col overflow-hidden border border-border/80 bg-white transition duration-300 hover:border-secondary/40 hover:shadow-[0_16px_40px_rgba(15,23,42,0.06)]',
        featured && 'lg:flex-row',
      )}
    >
      <div
        className={cn(
          'relative w-full shrink-0 overflow-hidden bg-muted',
          featured ? 'aspect-[16/10] lg:aspect-auto lg:min-h-[300px] lg:w-[46%]' : 'aspect-[16/10]',
        )}
      >
        {post.image ? (
          <Image
            src={resolveAssetPath(post.image)}
            alt={post.title}
            fill
            sizes={featured ? '(max-width: 1024px) 100vw, 46vw' : '(max-width: 768px) 100vw, 33vw'}
            quality={featured ? 65 : 60}
            className="object-cover transition-transform duration-700 group-hover:scale-[1.03]"
            loading="lazy"
          />
        ) : (
          <div className="absolute inset-0 bg-primary/10" />
        )}
      </div>

      <div className={cn('flex flex-1 flex-col p-6 sm:p-7', featured && 'lg:justify-center lg:p-10')}>
        <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 text-[11px] font-bold uppercase tracking-[0.16em] text-secondary">
          <span>{post.category || 'Article'}</span>
          {post.readTime ? (
            <span className="inline-flex items-center gap-1.5 font-semibold normal-case tracking-normal text-muted-foreground">
              <Clock className="h-3.5 w-3.5 text-accent" />
              {post.readTime}
            </span>
          ) : null}
          {post.isFeatured ? (
            <span className="border border-accent/30 bg-accent/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] text-accent">
              {t('featured')}
            </span>
          ) : null}
        </div>

        <h3
          className={cn(
            'mt-3 font-heading leading-snug text-foreground transition-colors group-hover:text-primary',
            featured ? 'text-2xl sm:text-3xl' : 'text-xl sm:text-[1.35rem]',
          )}
        >
          {post.title}
        </h3>
        <p className="mt-3 flex-1 text-sm leading-6 text-muted-foreground line-clamp-3 sm:text-base sm:leading-7">
          {post.description}
        </p>

        <div className="mt-6 flex flex-col gap-4 border-t border-border/70 pt-5 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex flex-wrap items-center gap-4 text-xs text-muted-foreground sm:text-sm">
            <span className="inline-flex items-center gap-1.5">
              <User className="h-3.5 w-3.5 text-accent" />
              {post.author}
            </span>
            {post.date ? (
              <span className="inline-flex items-center gap-1.5">
                <Calendar className="h-3.5 w-3.5 text-accent" />
                {formatDate(post.date)}
              </span>
            ) : null}
          </div>
          <span className="inline-flex items-center gap-2 text-sm font-semibold text-primary transition-all group-hover:gap-3">
            {t('readArticle')}
            <ArrowUpRight className="h-4 w-4" />
          </span>
        </div>
      </div>
    </Link>
  )
}

export default function BlogPage() {
  const { site } = useSiteData()
  const t = useTranslations('updates.blog')
  const {
    items,
    isLoading,
    isError,
    isEmpty,
    error,
    refetch,
    loadMore,
    hasMore,
    isLoadingMore,
    pagination,
  } = useFetchData<BlogPost>({
    endpoint: 'blog-posts',
    infinite: true,
    initialPageSize: 9,
  })

  const blogPosts = items ?? []
  const featured = useMemo(() => blogPosts.filter((post) => post.isFeatured).slice(0, 2), [blogPosts])

  const categories = useMemo(() => {
    const unique = Array.from(new Set(blogPosts.map((post) => post.category).filter(Boolean)))
    return unique
  }, [blogPosts])

  const [activeCategory, setActiveCategory] = useState('All')

  const visiblePosts = useMemo(() => {
    const featuredIds = new Set(featured.map((post) => post.id))
    const remaining = blogPosts.filter((post) => !featuredIds.has(post.id))
    if (activeCategory === 'All') return remaining
    return remaining.filter((post) => post.category === activeCategory)
  }, [activeCategory, blogPosts, featured])

  const articleCount = pagination?.count ?? blogPosts.length

  return (
    <main>
      <PageHero
        eyebrow={t('hero.eyebrow')}
        title={t('hero.title')}
        description={t('hero.description', { name: site.shortName })}
      />

      <section className="border-b border-border/70 bg-white py-16 sm:py-20 md:py-24">
        <div className="container-wide">
          <DataStates
            isLoading={isLoading}
            isError={isError}
            isEmpty={isEmpty}
            error={error}
            loadingMessage={t('loading')}
            emptyMessage={t('empty')}
            onRetry={refetch}
          >
            <div className="mb-10 grid gap-3 sm:grid-cols-3">
              {[
                { label: t('stats.articles'), value: String(articleCount) },
                { label: t('stats.topics'), value: String(categories.length) },
                { label: t('stats.featured'), value: String(featured.length) },
              ].map(({ label, value }) => (
                <div
                  key={label}
                  className="border border-border/80 bg-[oklch(0.985_0.008_343)] px-6 py-5 text-center sm:text-left"
                >
                  <p className="font-heading text-3xl text-primary">{value}</p>
                  <p className="mt-1.5 text-sm font-medium text-muted-foreground">{label}</p>
                </div>
              ))}
            </div>

            {categories.length > 0 ? (
              <div className="mb-12 border-b border-border/70 pb-10">
                <p className="mb-4 text-[11px] font-bold uppercase tracking-[0.22em] text-secondary">
                  {t('browse')}
                </p>
                <div className="flex flex-wrap gap-2">
                  <button
                    type="button"
                    onClick={() => setActiveCategory('All')}
                    className={cn(
                      'inline-flex h-10 items-center border px-4 text-sm font-semibold transition',
                      activeCategory === 'All'
                        ? 'border-primary bg-primary text-primary-foreground'
                        : 'border-border bg-white text-foreground hover:border-primary hover:text-primary',
                    )}
                  >
                    {t('allTopics')}
                  </button>
                  {categories.map((cat) => (
                    <button
                      key={cat}
                      type="button"
                      onClick={() => setActiveCategory(cat)}
                      className={cn(
                        'inline-flex h-10 items-center border px-4 text-sm font-semibold transition',
                        activeCategory === cat
                          ? 'border-primary bg-primary text-primary-foreground'
                          : 'border-border bg-white text-foreground hover:border-primary hover:text-primary',
                      )}
                    >
                      {cat}
                    </button>
                  ))}
                </div>
              </div>
            ) : null}

            {featured.length > 0 && activeCategory === 'All' ? (
              <div className="mb-14">
                <div className="mb-8">
                  <p className="text-[11px] font-bold uppercase tracking-[0.22em] text-secondary">
                    {t('featured')}
                  </p>
                  <span className="mt-3 block h-0.5 w-10 bg-accent" aria-hidden />
                  <h2 className="mt-4 font-heading text-3xl text-foreground sm:text-4xl">
                    {t('editorsPicks')}
                  </h2>
                </div>
                <div className="space-y-5">
                  {featured.slice(0, 2).map((post) => (
                    <BlogPostCard key={post.id} post={post} featured />
                  ))}
                </div>
              </div>
            ) : null}

            <div>
              <div className="mb-8">
                <p className="text-[11px] font-bold uppercase tracking-[0.22em] text-secondary">
                  {t('allArticles')}
                </p>
                <span className="mt-3 block h-0.5 w-10 bg-accent" aria-hidden />
                <h2 className="mt-4 font-heading text-3xl text-foreground sm:text-4xl">
                  {activeCategory === 'All' ? t('latest') : activeCategory}
                </h2>
              </div>

              {visiblePosts.length === 0 ? (
                <div className="border border-border/80 bg-[oklch(0.985_0.008_343)] px-6 py-12 text-center text-muted-foreground">
                  {t('emptyCategory')}
                </div>
              ) : (
                <div className="grid gap-5 md:grid-cols-2 xl:grid-cols-3">
                  {visiblePosts.map((post) => (
                    <BlogPostCard key={post.id} post={post} />
                  ))}
                </div>
              )}

              <InfiniteScrollSentinel
                hasMore={hasMore}
                isLoadingMore={isLoadingMore}
                onLoadMore={loadMore}
              />
            </div>
          </DataStates>
        </div>
      </section>

      <section className="border-b border-border/70 bg-[oklch(0.975_0.01_343)] py-16 sm:py-20">
        <div className="container-wide">
          <div className="mx-auto max-w-2xl text-center">
            <p className="text-[11px] font-bold uppercase tracking-[0.22em] text-secondary">
              {t('subscribe.eyebrow')}
            </p>
            <span className="mx-auto mt-3 block h-0.5 w-10 bg-accent" aria-hidden />
            <h2 className="mt-4 font-heading text-3xl text-foreground sm:text-4xl">
              {t('subscribe.title')}
            </h2>
            <p className="mx-auto mt-4 max-w-xl text-base leading-7 text-muted-foreground">
              {t('subscribe.description', { name: site.shortName })}
            </p>
            <form className="mx-auto mt-8 flex max-w-lg flex-col gap-3 sm:flex-row">
              <input
                type="email"
                placeholder={t('subscribe.placeholder')}
                className="h-12 flex-1 border border-border bg-white px-4 text-sm outline-none transition focus:border-primary"
              />
              <button
                type="submit"
                className="inline-flex h-12 items-center justify-center bg-primary px-6 text-sm font-semibold text-primary-foreground transition hover:bg-primary/90"
              >
                {t('subscribe.button')}
              </button>
            </form>
          </div>
        </div>
      </section>

      <section className="relative overflow-hidden bg-[oklch(0.22_0.07_343)] py-16 text-white sm:py-20">
        <div
          className="pointer-events-none absolute inset-0"
          style={{
            backgroundImage:
              'radial-gradient(ellipse 50% 45% at 20% 30%, oklch(0.50 0.09 179 / 0.3), transparent)',
          }}
          aria-hidden
        />
        <div className="container-wide relative">
          <div className="grid gap-8 lg:grid-cols-[1.2fr_auto] lg:items-center">
            <div>
              <p className="text-[11px] font-bold uppercase tracking-[0.22em] text-accent">
                {t('cases.eyebrow')}
              </p>
              <span className="mt-3 block h-0.5 w-10 bg-accent" aria-hidden />
              <h2 className="mt-4 font-heading text-3xl sm:text-4xl">
                {t('cases.title')}
              </h2>
              <p className="mt-4 max-w-2xl text-base leading-7 text-white/75">
                {t('cases.description', { name: site.shortName })}
              </p>
            </div>
            <Link
              href="/resources/case-studies"
              className="inline-flex h-12 items-center justify-center gap-2 border border-white/25 px-7 text-sm font-semibold transition hover:border-accent hover:text-accent"
            >
              {t('cases.cta')}
              <ArrowRight className="h-4 w-4" />
            </Link>
          </div>
        </div>
      </section>
    </main>
  )
}
