/* ====================================================
 * News Listing Page (Tin tức)
 * ==================================================== */

'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { HiOutlineCalendar, HiOutlineEye } from 'react-icons/hi';
import Breadcrumb from '@/components/layout/Breadcrumb';
import SectionHeader from '@/components/common/SectionHeader';
import Pagination from '@/components/ui/Pagination';
import ScrollReveal from '@/components/common/ScrollReveal';
import { formatDate, formatNumber } from '@/utils';
import { newsService } from '@/services/newsService';
import { NewsArticle, Category } from '@/types/api';

export default function NewsPage() {
  const [activeCategory, setActiveCategory] = useState('all');
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 6; // API pagination might dictate this

  const [articles, setArticles] = useState<NewsArticle[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [totalItems, setTotalItems] = useState(0);
  const [isLoading, setIsLoading] = useState(true);

  // Fetch Categories on mount
  useEffect(() => {
    newsService.getCategories()
      .then(res => setCategories(res.results))
      .catch(console.error);
  }, []);

  // Fetch news when category or page changes
  useEffect(() => {
    setIsLoading(true);
    newsService.getNews({
      page: currentPage,
      category: activeCategory !== 'all' ? activeCategory : undefined,
    }).then(res => {
      setArticles(res.results);
      setTotalItems(res.count);
    }).catch(console.error)
      .finally(() => setIsLoading(false));
  }, [currentPage, activeCategory]);

  const totalPages = Math.ceil(totalItems / itemsPerPage) || 1;

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <>
      <Breadcrumb items={[{ label: 'Tin tức', href: '/tin-tuc' }]} />
      
      <section className="section-padding bg-surface-50">
        <div className="container-custom">
          <SectionHeader
            subtitle="Tin tức & Sự kiện"
            title="Cập nhật thông tin mới nhất"
            description="Những tin tức về hoạt động của Vitalist Pharma, kiến thức y khoa và chăm sóc sức khỏe cộng đồng."
          />
          
          {/* Category Filter */}
          <div className="flex flex-wrap items-center justify-center gap-2 md:gap-4 mb-12">
            <button
              onClick={() => { setActiveCategory('all'); setCurrentPage(1); }}
              className={`px-5 py-2.5 rounded-full text-sm font-semibold transition-all ${
                activeCategory === 'all' 
                  ? 'bg-primary-500 text-white shadow-md' 
                  : 'bg-white text-dark-500 hover:bg-primary-50 border border-surface-200'
              }`}
            >
              Tất cả tin tức
            </button>
            {categories.map(cat => (
              <button
                key={cat.id}
                onClick={() => { setActiveCategory(cat.slug); setCurrentPage(1); }}
                className={`px-5 py-2.5 rounded-full text-sm font-semibold transition-all ${
                  activeCategory === cat.slug 
                    ? 'bg-primary-500 text-white shadow-md' 
                    : 'bg-white text-dark-500 hover:bg-primary-50 border border-surface-200'
                }`}
              >
                {cat.name}
              </button>
            ))}
          </div>

          {isLoading ? (
             <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-12">
                {[...Array(6)].map((_, i) => (
                  <div key={i} className="bg-surface-100 rounded-2xl animate-pulse h-96"></div>
                ))}
             </div>
          ) : articles.length > 0 ? (
            <>
              {/* Featured Article if Page 1 and All */}
              {currentPage === 1 && activeCategory === 'all' && (
                <div className="mb-12">
                  <ScrollReveal animation="fadeUp">
                    <Link href={`/tin-tuc/${articles[0].slug}`} className="group block">
                      <div className="bg-white rounded-3xl overflow-hidden shadow-card border border-surface-100 flex flex-col md:flex-row">
                        <div className="md:w-3/5 bg-gradient-to-br from-primary-100 to-accent-100 aspect-[16/9] md:aspect-auto flex items-center justify-center relative min-h-[300px]">
                          {articles[0].thumbnail ? (
                             <Image src={articles[0].thumbnail} alt={articles[0].title} fill className="object-cover group-hover:scale-105 transition-transform duration-500" />
                          ) : (
                             <span className="text-6xl z-10 relative">📰</span>
                          )}
                        </div>
                        <div className="md:w-2/5 p-8 md:p-10 flex flex-col justify-center">
                          <span className="inline-block px-3 py-1 bg-primary-50 text-primary-600 text-xs font-semibold rounded-full mb-4 w-fit">
                            {articles[0].category?.name}
                          </span>
                          <h3 className="text-2xl md:text-3xl font-bold text-dark-800 mb-4 group-hover:text-primary-600 transition-colors leading-tight">
                            {articles[0].title}
                          </h3>
                          <p className="text-dark-500 mb-6 line-clamp-3">
                            {articles[0].excerpt}
                          </p>
                          <div className="flex items-center gap-4 text-sm text-dark-400 mt-auto">
                            <span className="flex items-center gap-1.5">
                              <HiOutlineCalendar className="w-5 h-5" />
                              {formatDate(articles[0].created_at)}
                            </span>
                            <span className="flex items-center gap-1.5">
                              <HiOutlineEye className="w-5 h-5" />
                              {formatNumber(articles[0].view_count)}
                            </span>
                          </div>
                        </div>
                      </div>
                    </Link>
                  </ScrollReveal>
                </div>
              )}

              {/* Grid Articles */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-12">
                {articles.map((article, index) => {
                  // Skip first article if featured was already shown
                  if (currentPage === 1 && activeCategory === 'all' && index === 0) return null;
                  
                  return (
                    <ScrollReveal key={article.id} animation="fadeUp" delay={(index % 3) * 0.1}>
                      <Link href={`/tin-tuc/${article.slug}`} className="group block h-full">
                        <div className="bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-card transition-all border border-surface-200 h-full flex flex-col">
                          <div className="aspect-[4/3] bg-surface-100 flex items-center justify-center relative overflow-hidden">
                            {article.thumbnail ? (
                               <Image src={article.thumbnail} alt={article.title} fill className="object-cover group-hover:scale-105 transition-transform duration-500" />
                            ) : (
                               <span className="text-4xl z-10 relative">📰</span>
                            )}
                            <span className="absolute top-4 left-4 px-2.5 py-1 bg-white/90 backdrop-blur-sm text-primary-600 text-[10px] font-bold rounded-lg shadow-sm z-10">
                              {article.category?.name}
                            </span>
                          </div>
                          <div className="p-6 flex flex-col flex-1">
                            <h3 className="text-lg font-bold text-dark-800 mb-3 group-hover:text-primary-600 transition-colors line-clamp-2">
                              {article.title}
                            </h3>
                            <p className="text-dark-500 text-sm mb-4 line-clamp-3 flex-1">
                              {article.excerpt}
                            </p>
                            <div className="flex items-center justify-between text-xs text-dark-400 pt-4 border-t border-surface-100 mt-auto">
                              <span className="flex items-center gap-1">
                                <HiOutlineCalendar className="w-4 h-4" />
                                {formatDate(article.created_at)}
                              </span>
                              <span className="flex items-center gap-1">
                                <HiOutlineEye className="w-4 h-4" />
                                {formatNumber(article.view_count)}
                              </span>
                            </div>
                          </div>
                        </div>
                      </Link>
                    </ScrollReveal>
                  );
                })}
              </div>

              {totalPages > 1 && (
                <Pagination 
                  currentPage={currentPage}
                  totalPages={totalPages}
                  onPageChange={handlePageChange}
                />
              )}
            </>
          ) : (
            <div className="text-center py-20 bg-white rounded-2xl border border-surface-200">
              <div className="text-4xl mb-4">📰</div>
              <h3 className="text-lg font-bold text-dark-800 mb-2">Không tìm thấy tin tức nào</h3>
            </div>
          )}
          
        </div>
      </section>
    </>
  );
}
