'use client';

import React, { useState, useEffect } from 'react';
import { 
  Search, 
  BookOpen, 
  Users, 
  Calendar, 
  ArrowRight,
  Award,
  MessageSquare,
  Phone,
  Mail
} from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';

// Import Shared Components
import ModernCard from '../../components/shared/ModernCard';
import StatCard from '../../components/shared/StatCard';

const ARTICLES_PER_PAGE = 6;

interface Blog {
  id: string;
  title: string;
  short_description: string;
  description: string;
  image: string;
  category_id: string;
  user_id: string;
  is_active: boolean;
  is_featured: boolean;
  enable_meta_tags: boolean;
  created_at: string;
  updated_at: string;
  custom_post_type: string;
  seo: any;
  post_attributes: any;
  views: number;
  likes: number;
  rating_count: number;
  review_count: number;
  avg_review_value: number;
  slug: string;
  category?: string;
  author?: {
    name: string;
    slug: string;
    image: string;
  };
}

interface Category {
  id: string;
  name: string;
}

const ArticlePage = () => {
  const [blogs, setBlogs] = useState<Blog[]>([]);
  const [activeCategory, setActiveCategory] = useState<Category>({ id: 'All', name: 'All' });
  const [currentPage, setCurrentPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [totalBlogs, setTotalBlogs] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const [categories, setCategories] = useState<Category[]>([{ id: 'All', name: 'All' }]);

  // Fetch blogs with server-side pagination
  const fetchBlogs = async (page = 1, category = 'All', search = '') => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        limit: ARTICLES_PER_PAGE.toString(),
        page: page.toString()
      });

      if (search.trim()) {
        params.append('search', search.trim());
      }

      // Add category filter if not "All"
      if (category !== 'All') {
        params.append('category', category);
      }

      const res = await fetch(`/api/frontend/blogpage?${params.toString()}`);
      const data = await res.json();
      
      if (data && data.data) {
        setBlogs(data.data);
        
        let total = data.pagination?.totalItems || 0;
        setTotalBlogs(total);
        
        const calculatedPages = Math.ceil(total / ARTICLES_PER_PAGE);
        setTotalPages(calculatedPages);
      } else {
        setBlogs([]);
        setTotalBlogs(0);
        setTotalPages(0);
      }
    } catch (err) {
      console.error('Error fetching blogs:', err);
      setBlogs([]);
      setTotalBlogs(0);
      setTotalPages(0);
    } finally {
      setLoading(false);
    }
  };

  // Fetch categories
  const fetchCategories = async () => {
    try {
      const res = await fetch('/api/internal/blog-categories');
      const data = await res.json();
      
      if (data && data.data) {
        const allCategories: Category[] = [
          { id: 'All', name: 'All' },
          ...data.data.map((cat: any) => ({ 
            id: cat.id.toString(), 
            name: cat.name 
          }))
        ];
        setCategories(allCategories);
      }
    } catch (err) {
      console.error('Error fetching categories:', err);
    }
  };

  // Initial load
  useEffect(() => {
    fetchBlogs(1, 'All', '');
    fetchCategories();
  }, []);

  // Reset to first page when filters change
  useEffect(() => {
    setCurrentPage(1);
    fetchBlogs(1, activeCategory.id, searchQuery);
  }, [activeCategory.id, searchQuery]);

  const handleCategoryChange = (category: Category) => {
    setActiveCategory(category);
  };

  const handlePageChange = (page: number) => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page);
      fetchBlogs(page, activeCategory.id, searchQuery);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  const handleSearch = () => {
    setCurrentPage(1);
    fetchBlogs(1, activeCategory.id, searchQuery);
  };

  // Handle Enter key press in search
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  // Helper function to get S3 URL
  const getS3Url = (imagePath: string) => {
    if (!imagePath) return null;
    
    if (imagePath.startsWith('/')) {
      return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET || 'your-bucket'}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION || 'us-east-1'}.amazonaws.com/${imagePath.replace(/^\/+/, "")}`;
    }
    
    if (imagePath.startsWith('http')) {
      return imagePath;
    }
    
    return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET || 'your-bucket'}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION || 'us-east-1'}.amazonaws.com/${imagePath}`;
  };

  // Stats data
  const stats = [
    { Icon: BookOpen, number: '300+', label: 'Articles Published', color: 'teal' },
    { Icon: Users, number: '50K+', label: 'Monthly Readers', color: 'blue' },
    { Icon: Calendar, number: '99%', label: 'Success Stories', color: 'emerald' },
    { Icon: Award, number: '100+', label: 'Expert Writers', color: 'amber' }
  ];

  return (
    <div className="min-h-screen bg-linear-to-b from-gray-50 to-white">
      {/* Hero Section */}
      <div className="relative">
        <div className="absolute inset-0 bg-linear-to-r from-teal-50/50 to-blue-50/50"></div>
        
        <div className="absolute top-0 left-0 w-full h-full overflow-hidden">
          {[...Array(20)].map((_, i) => (
            <div
              key={i}
              className="absolute rounded-full bg-linear-to-r from-teal-200/20 to-blue-200/20 animate-float"
              style={{
                width: Math.random() * 100 + 50,
                height: Math.random() * 100 + 50,
                top: `${Math.random() * 100}%`,
                left: `${Math.random() * 100}%`,
                animationDelay: `${Math.random() * 5}s`,
                animationDuration: `${Math.random() * 10 + 10}s`
              }}
            />
          ))}
        </div>

        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20 md:py-28">
          <div className="text-center">
            <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-6 py-3 rounded-full text-sm font-semibold mb-8 animate-pulse">
              <BookOpen className="w-5 h-5" />
              Education Insights Blog
            </div>

            <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-8 leading-tight">
              Discover{' '}
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Insightful Articles
              </span>
            </h1>

            <p className="text-xl md:text-2xl text-gray-600 mb-12 max-w-3xl mx-auto leading-relaxed">
              Explore <strong className="text-teal-600">300+ articles</strong> on education, career guidance, 
              and study abroad insights from industry experts.
            </p>

            {/* Search Bar */}
            <div className="max-w-2xl mx-auto mt-8">
              <div className="relative flex items-center gap-2">
                <div className="grow relative">
                  <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 z-10" />
                  <input
                    type="text"
                    placeholder="Search articles, topics, or keywords..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    onKeyPress={handleKeyPress}
                    className="w-full pl-12 pr-4 py-4 rounded-xl border border-gray-300 bg-white/80 backdrop-blur-sm shadow-lg focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-teal-500 text-gray-700 transition-all duration-300"
                  />
                </div>
                <button
                  onClick={handleSearch}
                  className="bg-linear-to-r from-teal-600 to-blue-500 text-white px-6 py-4 rounded-xl hover:opacity-90 transition-all duration-300 font-semibold whitespace-nowrap"
                >
                  Search
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Stats Section */}
      <div className="py-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold text-gray-900 mb-4">
              Our Content Impact
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Trusted by thousands of students and professionals worldwide
            </p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            {stats.map((stat, index) => (
              <StatCard 
                key={index}
                Icon={stat.Icon}
                number={stat.number}
                label={stat.label}
                color={stat.color}
              />
            ))}
          </div>
        </div>
      </div>

      {/* Main Content Section */}
      <div className="py-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold text-gray-900 mb-4">
              Browse{' '}
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Latest Articles
              </span>
            </h2>
            <p className="text-gray-600 text-lg max-w-2xl mx-auto">
              {searchQuery ? `Showing results for "${searchQuery}"` : 'Discover insightful content across various categories and topics'}
            </p>
          </div>

          {/* Category Filter Buttons */}
          <div className="flex flex-wrap justify-center gap-3 mb-12">
            {categories.map((category) => (
              <button
                key={category.id}
                onClick={() => handleCategoryChange(category)}
                className={`px-5 py-2.5 rounded-xl font-medium transition-all duration-300 ${
                  activeCategory.id === category.id
                    ? 'text-white shadow-lg'
                    : 'text-gray-700 bg-white border border-gray-200 hover:border-teal-500 hover:text-teal-600'
                }`}
                style={
                  activeCategory.id === category.id 
                    ? { background: 'linear-linear(135deg, #0ea5e9, #06b6d4)' }
                    : {}
                }
              >
                {category.name}
              </button>
            ))}
          </div>

          {/* Results Info */}
          <div className="text-center mb-8">
            <p className="text-gray-600 mb-2">
              Showing {activeCategory.name} articles
              {searchQuery && ` for "${searchQuery}"`}
            </p>
            <p className="font-semibold text-teal-600">
              Page {currentPage} of {totalPages || 1} • 
              Showing {(currentPage - 1) * ARTICLES_PER_PAGE + 1}-
              {Math.min(currentPage * ARTICLES_PER_PAGE, totalBlogs)} of {totalBlogs} articles
            </p>
          </div>

          {/* Articles Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            {loading ? (
              Array.from({ length: ARTICLES_PER_PAGE }).map((_, idx) => (
                <div key={idx} className="animate-pulse overflow-hidden rounded-2xl bg-white shadow-lg">
                  <div className="w-full h-48 bg-linear-to-br from-gray-200 to-gray-300"></div>
                  <div className="p-6">
                    <div className="h-6 bg-gray-300 rounded w-3/4 mb-4"></div>
                    <div className="h-4 bg-gray-300 rounded w-full mb-2"></div>
                    <div className="h-4 bg-gray-300 rounded w-5/6 mb-4"></div>
                    <div className="h-10 bg-gray-300 rounded"></div>
                  </div>
                </div>
              ))
            ) : blogs.length === 0 ? (
              <div className="col-span-full text-center py-16">
                <div className="text-6xl mb-4">📝</div>
                <div className="text-2xl font-bold mb-2 bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                  No articles found
                </div>
                <p className="text-gray-500 max-w-md mx-auto">
                  {searchQuery ? `No articles match your search for "${searchQuery}". Try different keywords.` 
                    : 'No articles are available in this category yet.'}
                </p>
              </div>
            ) : (
              blogs.map((blog) => {
                const blogImageUrl = getS3Url(blog.image);
                const authorImageUrl = blog.author?.image ? getS3Url(blog.author.image) : null;
                
                return (
                  <div key={blog.id} className="group h-full">
                    <ModernCard className="overflow-hidden hover:shadow-xl transition-all duration-300 cursor-pointer h-full flex flex-col">
                      {/* Blog Image with Link */}
                      <Link href={`/${blog.slug}`} className="block">
                        <div className="relative h-48 w-full overflow-hidden">
                          {blogImageUrl ? (
                            <>
                              <Image
                                src={blogImageUrl}
                                alt={blog.title || 'Blog Article'}
                                fill
                                sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                                className="object-cover transition-transform duration-500 group-hover:scale-110"
                                unoptimized={blogImageUrl.includes('s3.amazonaws.com')}
                              />
                              <div className="absolute inset-0 bg-linear-to-t from-black/70 via-black/30 to-transparent"></div>
                            </>
                          ) : (
                            <div className="w-full h-full bg-linear-to-br from-teal-100 to-blue-100 flex items-center justify-center">
                              <BookOpen className="w-12 h-12 text-teal-300" />
                            </div>
                          )}
                          {/* Category Badge */}
                          <div className="absolute top-3 left-3 z-10">
                            <div className="bg-linear-to-r from-teal-600 to-blue-500 text-white text-xs font-semibold px-3 py-1.5 rounded-full">
                              {'Education'}
                            </div>
                          </div>
                        </div>
                      </Link>
                      
                      {/* Content Section */}
                      <div className="p-6 grow flex flex-col">
                        {/* Blog Title with Link */}
                        <Link href={`/${blog.slug}`} className="block mb-3">
                          <div className="flex justify-between items-start">
                            <h3 className="text-xl font-bold text-gray-900 leading-tight line-clamp-2 hover:text-teal-600 transition-colors">
                              {blog.title}
                            </h3>
                            <ArrowRight className="w-5 h-5 text-gray-400 transition-transform group-hover:translate-x-2 shrink-0 mt-1" />
                          </div>
                        </Link>
                        
                        {blog.short_description && (
                          <p className="text-gray-600 text-sm mt-2 line-clamp-3 grow">
                            {blog.short_description}
                          </p>
                        )}
                        
                        {/* Author and Date - Author is now clickable */}
                        <div className="mt-4 pt-4 border-t border-gray-100 flex justify-between items-center text-xs text-gray-500">
                          <div className="flex items-center gap-2">
                            {/* Author Image */}
                            {authorImageUrl ? (
                              <Link 
                                href={`/author/${blog.author?.slug || 'admin'}`}
                                onClick={(e) => e.stopPropagation()}
                                className="relative w-6 h-6 rounded-full overflow-hidden shrink-0"
                              >
                                <Image
                                  src={authorImageUrl}
                                  alt={blog.author?.name || 'Author'}
                                  fill
                                  sizes="24px"
                                  className="object-cover"
                                  unoptimized={authorImageUrl.includes('s3.amazonaws.com')}
                                />
                              </Link>
                            ) : (
                              <div className="w-6 h-6 rounded-full bg-linear-to-r from-teal-100 to-blue-100 flex items-center justify-center shrink-0">
                                <Users className="w-3 h-3 text-teal-500" />
                              </div>
                            )}
                            
                            {/* Author Name Link */}
                            <Link 
                              href={`/author/${blog.author?.slug || 'admin'}`}
                              onClick={(e) => e.stopPropagation()}
                              className="flex items-center gap-1 text-gray-600 hover:text-teal-600 transition-colors font-medium"
                            >
                              <span>{blog.author?.name || 'Admin'}</span>
                            </Link>
                          </div>
                          
                          <span className="flex items-center gap-1">
                            <Calendar className="w-3 h-3" />
                            {blog.created_at ? new Date(blog.created_at).toLocaleDateString() : 'Recent'}
                          </span>
                        </div>
                      </div>
                    </ModernCard>
                  </div>
                );
              })
            )}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="mt-12 flex justify-center">
              <div className="flex items-center gap-2">
                <button
                  onClick={() => handlePageChange(currentPage - 1)}
                  disabled={currentPage === 1}
                  className="px-4 py-2 rounded-lg border border-gray-300 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 transition-colors"
                >
                  Previous
                </button>
                
                {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                  let pageNum;
                  if (totalPages <= 5) {
                    pageNum = i + 1;
                  } else if (currentPage <= 3) {
                    pageNum = i + 1;
                  } else if (currentPage >= totalPages - 2) {
                    pageNum = totalPages - 4 + i;
                  } else {
                    pageNum = currentPage - 2 + i;
                  }
                  
                  return (
                    <button
                      key={pageNum}
                      onClick={() => handlePageChange(pageNum)}
                      className={`px-4 py-2 rounded-lg transition-colors ${
                        currentPage === pageNum
                          ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white'
                          : 'border border-gray-300 hover:bg-gray-50'
                      }`}
                    >
                      {pageNum}
                    </button>
                  );
                })}
                
                <button
                  onClick={() => handlePageChange(currentPage + 1)}
                  disabled={currentPage === totalPages}
                  className="px-4 py-2 rounded-lg border border-gray-300 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 transition-colors"
                >
                  Next
                </button>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* CTA Section */}
      <div className="py-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="bg-linear-to-r from-teal-600 to-blue-500 rounded-3xl p-8 md:p-12 text-center">
            <h2 className="text-3xl md:text-4xl font-bold text-white mb-4">
              Stay Updated with Latest Insights
            </h2>
            <p className="text-white/80 text-lg mb-8 max-w-2xl mx-auto">
              Subscribe to our newsletter and never miss important updates on education trends and opportunities.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center">
              <Link href="/contact" className="inline-flex items-center justify-center gap-2 bg-white text-teal-700 font-semibold py-3 px-8 rounded-xl hover:bg-gray-100 transition-all duration-300 transform hover:scale-105">
                <MessageSquare className="w-4 h-4" />
                Subscribe to Newsletter
              </Link>
              <Link href="/blog" className="inline-flex items-center justify-center gap-2 border-2 border-white/30 text-white font-semibold py-3 px-8 rounded-xl hover:bg-white/10 transition-all duration-300 transform hover:scale-105">
                <BookOpen className="w-4 h-4" />
                Browse All Articles
              </Link>
            </div>
            
            {/* Contact Info */}
            <div className="mt-12 pt-8 border-t border-white/20">
              <p className="text-white/80 mb-6">Have questions? Contact us directly</p>
              <div className="flex flex-col sm:flex-row gap-4 justify-center">
                <a 
                  href="tel:+923330033235" 
                  className="inline-flex items-center justify-center gap-2 bg-white/20 backdrop-blur-sm text-white font-semibold py-3 px-6 rounded-xl hover:bg-white/30 transition-all duration-300"
                >
                  <Phone className="w-4 h-4" />
                  Call Now
                </a>
                <a 
                  href="mailto:info@universitiespage.com" 
                  className="inline-flex items-center justify-center gap-2 border-2 border-white/30 text-white font-semibold py-3 px-6 rounded-xl hover:bg-white/10 transition-all duration-300"
                >
                  <Mail className="w-4 h-4" />
                  Email Us
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ArticlePage;