'use client';

import React, { useState, useEffect, Suspense } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { Header } from '../components/Header';
import { Footer } from '../components/Footer';
import api, { type PaginatedCollection } from '@/lib/api';

const BLOG_PER_PAGE = 12;

interface BlogPost {
  id: number;
  title: string;
  slug: string;
  excerpt: string;
  content: string;
  featured_image: string | null;
  thumbnail: string | null;
  category: string | null;
  tags: string[];
  reading_time: number;
  reading_time_formatted: string;
  views_count: number;
  published_at: string;
  published_at_human: string;
  author?: {
    id: number;
    name: string;
    email: string;
  } | null;
}

function buildListPath(categoryForUrl: string | null, pageNum: number): string {
  const p = new URLSearchParams();
  if (categoryForUrl) p.set('category', categoryForUrl);
  if (pageNum > 1) p.set('page', String(pageNum));
  const qs = p.toString();
  return qs ? `/blog?${qs}` : '/blog';
}

function BlogContent() {
  const searchParams = useSearchParams();
  const categoryParam = searchParams?.get('category');
  const pageRaw = searchParams?.get('page');
  const page = Math.max(1, parseInt(pageRaw || '1', 10) || 1);
  const normalizedCategory =
    categoryParam === 'stories' ? 'story' : categoryParam;

  const isStoriesView = normalizedCategory === 'story';
  const categoryForLinks =
    normalizedCategory && normalizedCategory.length > 0 ? normalizedCategory : null;

  const [blogPosts, setBlogPosts] = useState<BlogPost[]>([]);
  const [listMeta, setListMeta] = useState<PaginatedCollection<BlogPost>['meta'] | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isVisible, setIsVisible] = useState(false);
  const [retryKey, setRetryKey] = useState(0);

  useEffect(() => {
    let cancelled = false;

    async function loadPosts() {
      try {
        setLoading(true);
        setError(null);

        let apiCategory: string | undefined;
        let apiExclude: string | undefined;

        if (normalizedCategory === 'story') {
          apiCategory = 'story';
        } else if (normalizedCategory) {
          apiCategory = normalizedCategory;
        } else {
          apiExclude = 'story';
        }

        const response = await api.getBlogPosts<BlogPost>({
          status: 'published',
          paginate: true,
          per_page: BLOG_PER_PAGE,
          page,
          order_by: 'published_at',
          order_direction: 'desc',
          ...(apiCategory ? { category: apiCategory } : {}),
          ...(apiExclude ? { exclude_category: apiExclude } : {}),
        });

        if (cancelled) return;

        if (Array.isArray(response)) {
          setBlogPosts(response);
          setListMeta(null);
        } else {
          setBlogPosts(response.data);
          setListMeta(response.meta);
        }
      } catch (err: unknown) {
        if (cancelled) return;
        console.error('Error fetching blog posts:', err);
        setError(err instanceof Error ? err.message : 'Failed to load blog posts');
        setBlogPosts([]);
        setListMeta(null);
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }

    loadPosts();

    return () => {
      cancelled = true;
    };
  }, [normalizedCategory, page, retryKey]);

  useEffect(() => {
    if (!loading) {
      setTimeout(() => setIsVisible(true), 100);
    }
  }, [loading]);

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

  const getPageDescription = () => {
    if (normalizedCategory === 'story') {
      return 'Community voices, impact, and transformation from across Afghanistan';
    }
    return 'Discover the latest news, updates, and insights from our work across Afghanistan';
  };

  const showFeaturedLayout = page === 1 && blogPosts.length > 0;

  const FeaturedPost = ({ post }: { post: BlogPost }) => {
    const imageUrl = post.featured_image || post.thumbnail || '/images/IMG_9722.JPG';

    return (
      <Link href={`/blog/${post.slug}`} className="group mb-12 block lg:mb-16">
        <article className="overflow-hidden rounded-3xl border border-secondary-200 bg-white shadow-sm transition-shadow duration-300 group-hover:shadow-xl">
          <div className="grid grid-cols-1 lg:grid-cols-2">
            <div className="relative min-h-[16rem] overflow-hidden sm:min-h-[22rem] lg:min-h-[28rem]">
              <img
                src={imageUrl}
                alt={post.title}
                className="absolute inset-0 h-full w-full object-cover transition-transform duration-700 group-hover:scale-105"
              />
              <div className="absolute bottom-0 left-0 right-0 h-1.5 bg-primary-500" />
            </div>

            <div className="flex flex-col justify-center px-6 py-8 sm:px-10 sm:py-12 lg:px-12">
              <div className="flex flex-wrap items-center gap-3">
                <span className="rounded-full bg-primary-500 px-3 py-1 text-xs font-bold uppercase tracking-wide text-neutral-900">
                  {isStoriesView ? 'Featured story' : 'Latest'}
                </span>
                {post.category && post.category !== 'story' && (
                  <span className="text-xs font-semibold uppercase tracking-widest text-neutral-400">
                    {post.category}
                  </span>
                )}
              </div>

              <h2
                className="mt-4 text-2xl font-black leading-tight text-neutral-900 transition-colors group-hover:text-primary-600 sm:text-3xl md:text-4xl"
                dir="auto"
              >
                {post.title}
              </h2>

              {post.excerpt && (
                <p className="mt-4 line-clamp-3 text-base leading-relaxed text-neutral-600" dir="auto">
                  {post.excerpt}
                </p>
              )}

              <div className="mt-6 flex flex-wrap items-center gap-4 text-sm text-neutral-500">
                {post.published_at && <span>{formatDate(post.published_at)}</span>}
                {post.reading_time > 0 && (
                  <span>{post.reading_time_formatted || `${post.reading_time} min read`}</span>
                )}
                {post.author && <span>{post.author.name}</span>}
              </div>

              <span className="mt-8 inline-flex items-center gap-2 text-sm font-bold text-navy-800">
                Read {isStoriesView ? 'story' : 'article'}
                <svg
                  className="h-4 w-4 transition-transform duration-300 group-hover:translate-x-1"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                  aria-hidden
                >
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
                </svg>
              </span>
            </div>
          </div>
        </article>
      </Link>
    );
  };

  const BlogCard = ({ post }: { post: BlogPost }) => {
    const imageUrl = post.featured_image || post.thumbnail || '/images/IMG_9722.JPG';

    return (
      <Link
        href={`/blog/${post.slug}`}
        className="group block h-full"
      >
        <article className="bg-white rounded-xl shadow-md hover:shadow-xl transition-all duration-500 transform hover:-translate-y-2 border border-neutral-100 h-full flex flex-col overflow-hidden">
          {/* Image */}
          <div className="relative h-52 w-full overflow-hidden bg-neutral-100 flex-shrink-0">
            <img 
              src={imageUrl}
              alt={post.title}
              className="w-full h-full object-cover scale-100 group-hover:scale-110 transition-transform duration-700"
            />
          </div>

          {/* Content */}
          <div className="p-6 flex-1 flex flex-col">
            {/* Meta Info */}
            <div className="flex items-center gap-3 text-xs text-neutral-500 mb-3 font-medium">
              {post.published_at && (
                <span className="flex items-center gap-1.5">
                  <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                  </svg>
                  {formatDate(post.published_at)}
                </span>
              )}
              {post.reading_time > 0 && (
                <span className="flex items-center gap-1.5">
                  <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  {post.reading_time_formatted || `${post.reading_time} min`}
                </span>
              )}
            </div>

            {/* Title */}
            <h2 className="text-xl font-bold text-neutral-900 mb-3 group-hover:text-primary-600 transition-colors line-clamp-3 leading-tight flex-1" dir="auto">
              {post.title}
            </h2>

            {/* Excerpt */}
            {post.excerpt && (
              <p className="text-neutral-600 leading-relaxed mb-4 line-clamp-2 text-sm" dir="auto">
                {post.excerpt}
              </p>
            )}

            {/* Author */}
            {post.author && (
              <div className="flex items-center gap-2 pt-3 border-t border-neutral-100">
                <div className="w-7 h-7 rounded-full bg-gradient-to-br from-primary-100 to-primary-200 flex items-center justify-center">
                  <span className="text-primary-700 text-xs font-bold">
                    {post.author.name.charAt(0).toUpperCase()}
                  </span>
                </div>
                <span className="text-xs font-medium text-neutral-700">{post.author.name}</span>
              </div>
            )}
          </div>
        </article>
      </Link>
    );
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-white">
        <Header />
        <div className="min-h-[80vh] flex items-center justify-center px-4">
          <div className="text-center">
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mb-4"></div>
            <p className="text-neutral-600">Loading posts...</p>
          </div>
        </div>
        <Footer />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-white">
      <Header />

      {/* Hero Section */}
      <section className="relative overflow-hidden border-b border-secondary-200 bg-white pt-28 pb-12 sm:pt-32 sm:pb-16">
        <div className="pointer-events-none absolute -left-24 top-10 h-64 w-64 rounded-full bg-primary-500/10 blur-3xl" />
        <div className="pointer-events-none absolute -right-16 bottom-0 h-56 w-56 rounded-full bg-navy-800/5 blur-3xl" />

        <div
          className={`relative mx-auto max-w-7xl px-4 transition-all duration-700 sm:px-6 lg:px-8 ${
            isVisible ? 'translate-y-0 opacity-100' : 'translate-y-6 opacity-0'
          }`}
        >
          <span className="inline-flex items-center gap-2 rounded-full border border-primary-500/30 bg-primary-500/10 px-4 py-1.5 text-xs font-bold uppercase tracking-widest text-primary-700">
            <span className="h-1.5 w-1.5 rounded-full bg-primary-500" />
            {isStoriesView ? 'Success stories' : 'News & updates'}
          </span>

          <h1 className="mt-5 text-4xl font-black leading-tight text-neutral-900 sm:text-5xl md:text-6xl">
            {isStoriesView ? (
              <>
                Voices from the{' '}
                <span className="relative inline-block text-primary-600">
                  field
                  <svg
                    className="absolute -bottom-2 left-0 w-full text-primary-400"
                    viewBox="0 0 120 12"
                    preserveAspectRatio="none"
                    aria-hidden
                  >
                    <path d="M2 9C30 2 90 2 118 9" stroke="currentColor" strokeWidth="4" strokeLinecap="round" fill="none" />
                  </svg>
                </span>
              </>
            ) : (
              <>
                Latest from{' '}
                <span className="relative inline-block text-primary-600">
                  SSEOA
                  <svg
                    className="absolute -bottom-2 left-0 w-full text-primary-400"
                    viewBox="0 0 140 12"
                    preserveAspectRatio="none"
                    aria-hidden
                  >
                    <path d="M2 9C36 2 104 2 138 9" stroke="currentColor" strokeWidth="4" strokeLinecap="round" fill="none" />
                  </svg>
                </span>
              </>
            )}
          </h1>

          <p className="mt-6 max-w-2xl text-lg leading-relaxed text-neutral-600">
            {getPageDescription()}
          </p>

          <div className="mt-8 inline-flex rounded-full border border-secondary-300 bg-secondary-50 p-1" role="tablist" aria-label="Content type">
            <Link
              href="/blog"
              className={`rounded-full px-5 py-2 text-sm font-bold transition-colors ${
                !isStoriesView
                  ? 'bg-navy-800 text-white'
                  : 'text-neutral-600 hover:text-neutral-900'
              }`}
              role="tab"
              aria-selected={!isStoriesView}
            >
              Blog
            </Link>
            <Link
              href="/blog?category=story"
              className={`rounded-full px-5 py-2 text-sm font-bold transition-colors ${
                isStoriesView
                  ? 'bg-navy-800 text-white'
                  : 'text-neutral-600 hover:text-neutral-900'
              }`}
              role="tab"
              aria-selected={isStoriesView}
            >
              Stories
            </Link>
          </div>
        </div>
      </section>

      {/* Blog Posts Grid */}
      <section className={`py-12 md:py-16 transition-all duration-1000 ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'}`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {blogPosts.length > 0 ? (
            <>
              {showFeaturedLayout && <FeaturedPost post={blogPosts[0]} />}

              <div className="grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-8 lg:grid-cols-3">
                {(showFeaturedLayout ? blogPosts.slice(1) : blogPosts).map((post, index) => (
                  <BlogCard key={post.id || index} post={post} />
                ))}
              </div>

              {listMeta && listMeta.last_page > 1 && (
                <nav
                  className="flex flex-col sm:flex-row items-center justify-center gap-4 mt-12 pt-8 border-t border-neutral-200"
                  aria-label="Pagination"
                >
                  {listMeta.current_page > 1 ? (
                    <Link
                      href={buildListPath(categoryForLinks, listMeta.current_page - 1)}
                      className="inline-flex items-center px-5 py-2.5 rounded-lg border border-neutral-300 text-neutral-800 font-medium hover:bg-neutral-50 transition-colors"
                    >
                      Previous
                    </Link>
                  ) : (
                    <span className="inline-flex items-center px-5 py-2.5 rounded-lg border border-transparent text-neutral-400 font-medium cursor-not-allowed">
                      Previous
                    </span>
                  )}
                  <p className="text-sm text-neutral-600 tabular-nums">
                    Page {listMeta.current_page} of {listMeta.last_page}
                    <span className="text-neutral-400"> · </span>
                    {listMeta.total} posts
                  </p>
                  {listMeta.current_page < listMeta.last_page ? (
                    <Link
                      href={buildListPath(categoryForLinks, listMeta.current_page + 1)}
                      className="inline-flex items-center px-5 py-2.5 rounded-lg border border-neutral-300 text-neutral-800 font-medium hover:bg-neutral-50 transition-colors"
                    >
                      Next
                    </Link>
                  ) : (
                    <span className="inline-flex items-center px-5 py-2.5 rounded-lg border border-transparent text-neutral-400 font-medium cursor-not-allowed">
                      Next
                    </span>
                  )}
                </nav>
              )}
            </>
          ) : (
            <div className="text-center py-24 bg-neutral-50 rounded-2xl border border-neutral-200">
              <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-primary-100 mb-6">
                <svg className="w-10 h-10 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9a2 2 0 00-2-2h-2m-4-3H9M7 16h6M7 8h6v4H7V8z" />
                </svg>
              </div>
              <h3 className="text-2xl font-bold text-neutral-900 mb-3">No posts yet</h3>
              <p className="text-neutral-600 text-lg">Check back soon for updates and stories from our work.</p>
            </div>
          )}
        </div>
      </section>

      {/* Error Message */}
      {error && (
        <section className="py-20">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="bg-red-50 border-2 border-red-200 rounded-2xl p-8 text-center">
              <p className="text-xl text-red-600 mb-4 font-semibold">Error: {error}</p>
              <button
                type="button"
                onClick={() => setRetryKey((k) => k + 1)}
                className="inline-flex items-center px-6 py-3 border border-transparent text-sm font-medium rounded-xl shadow-sm text-neutral-900 bg-primary-500 hover:bg-primary-400 transition-colors"
              >
                Retry
              </button>
            </div>
          </div>
        </section>
      )}

      <Footer />
    </div>
  );
}

export default function BlogPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen bg-white">
        <Header />
        <div className="min-h-[80vh] flex items-center justify-center px-4">
          <div className="text-center">
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mb-4"></div>
            <p className="text-neutral-600">Loading...</p>
          </div>
        </div>
        <Footer />
      </div>
    }>
      <BlogContent />
    </Suspense>
  );
}
