'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';

interface Bulletin {
  id: number;
  slug: string;
  title: string;
  excerpt: string | null;
  image_url: string | null;
  published_at: string;
}

const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost/agrivet_web/backend';

const STATIC: Bulletin[] = [
  { id: 1,  slug: 'avian-influenza-a-major-economic-threat-to-poultry-industry-part-1',                 title: 'Avian influenza a major economic threat to poultry industry (Part-1)',                 excerpt: 'Avian influenza also known as bird flu or fowl plague is highly contagious viral disease of birds. It is carried by wild aquatic birds, especially waterfowl, which are not greatly affected by the virus.', image_url: 'https://agrivet.in/agrivet_main_website/public/bulletin/202411190845511.webp', published_at: '2023-03-16' },
  { id: 2,  slug: 'novel-approach-to-strengthen-immunity',                                              title: 'Novel approach to strengthen immunity',                                               excerpt: 'The poultry industry needs innovative and practical solutions if it is to expand sustainably and in accordance with consumer demands for animal welfare and a reduction in the use of antibiotics.', image_url: 'https://agrivet.in/agrivet_main_website/public/bulletin/202411190858461.webp', published_at: '2023-03-04' },
  { id: 3,  slug: 'sustainable-poultry-farming',                                                        title: 'Sustainable poultry farming',                                                         excerpt: 'Due to an increase in demand over the past 100 years, animal food production has increased.', image_url: 'https://agrivet.in/agrivet_main_website/public/bulletin/202411190901071.webp', published_at: '2023-02-20' },
  { id: 4,  slug: 'poultry-nutrition-for-better-growth-and-sustainability',                             title: 'Poultry nutrition for better growth and sustainability',                              excerpt: 'Commercial uses for feed additives that can influence the gastrointestinal system of poultry and improve their performance have drawn increased attention.', image_url: 'https://agrivet.in/agrivet_main_website/public/bulletin/202411190902501.webp', published_at: '2023-02-02' },
  { id: 5,  slug: 'alternative-feed-in-poultry-diets',                                                 title: 'Alternative feed in poultry diets',                                                  excerpt: 'The population of the world is projected to rise to 9.1 billion by the year 2050.', image_url: 'https://agrivet.in/agrivet_main_website/public/bulletin/202411190933391.webp', published_at: '2023-01-22' },
  { id: 6,  slug: 'health-benefits-of-probiotics-and-criteria-for-their-selection-in-poultry-industry', title: 'Health benefits of probiotics and criteria for their selection in poultry industry', excerpt: 'Elie Metchnikoff, who worked at the Pasteur Institute in Paris, was the pioneering researcher in the fields of fermentation and probiotics.', image_url: 'https://agrivet.in/agrivet_main_website/public/bulletin/202411190935561.webp', published_at: '2023-01-01' },
  { id: 7,  slug: 'probiotics-in-poultry-feed',                                                        title: 'Probiotics in poultry feed',                                                         excerpt: 'Microbial feed supplement and growth promoter.', image_url: 'https://agrivet.in/agrivet_main_website/public/bulletin/202411190937391.webp', published_at: '2022-12-15' },
  { id: 8,  slug: 'potential-threats-to-broiler-gut-health',                                           title: 'Potential Threats to Broiler Gut Health',                                            excerpt: 'The gastrointestinal tract (GIT, gut) offers a biological environment for the breakdown and absorption of nutrients as well as defense against pathogens and toxins.', image_url: 'https://agrivet.in/agrivet_main_website/public/bulletin/202411190940361.webp', published_at: '2022-11-15' },
  { id: 9,  slug: 'gut-health-the-driver-of-performance-profitability-in-a-poultry-operation',         title: 'Gut Health: The driver of performance & profitability in a poultry operation',       excerpt: 'The Digestive System is the engine that drives the performance of any commercial poultry flock.', image_url: 'https://agrivet.in/agrivet_main_website/public/bulletin/202411190942061.webp', published_at: '2022-11-01' },
  { id: 10, slug: 'microbiome-in-poultry-gut-health',                                                  title: 'Microbiome in Poultry Gut Health',                                                   excerpt: 'The chicken gut microbiome plays a crucial part in the preservation of intestinal health because of its ability to control host physiological systems and maintain intestinal homeostasis.', image_url: 'https://agrivet.in/agrivet_main_website/public/bulletin/202411190944081.webp', published_at: '2022-11-29' },
];

function formatDate(dateStr: string) {
  return new Date(dateStr).toLocaleDateString('en-IN', { year: 'numeric', month: 'long', day: 'numeric' });
}

function BulletinCard({ item }: { item: Bulletin }) {
  const [imgFailed, setImgFailed] = useState(false);
  return (
    <Link href={`/technical-bulletin/${item.slug}`} className="tb-card">
      <div className="tb-card-img">
        {item.image_url && !imgFailed ? (
          <img src={item.image_url} alt={item.title} className="tb-card-img-el"
            onError={() => setImgFailed(true)} />
        ) : (
          <div className="tb-card-placeholder">
            <img src="/images/agrivet-logo.webp" alt="" className="tb-placeholder-logo" aria-hidden="true" />
          </div>
        )}
      </div>
      <div className="tb-card-body">
        <span className="tb-card-date">
          <i className="fas fa-calendar-days" aria-hidden="true" />
          {formatDate(item.published_at)}
        </span>
        <h3 className="tb-card-title">{item.title}</h3>
        {item.excerpt && <p className="tb-card-excerpt">{item.excerpt}</p>}
        <span className="tb-card-readmore">
          Read article <i className="fas fa-arrow-right" aria-hidden="true" />
        </span>
      </div>
    </Link>
  );
}

export default function TechnicalBulletinPage() {
  const [items, setItems] = useState<Bulletin[]>(STATIC);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`${API_BASE}/api/technical-bulletins`)
      .then(r => r.json())
      .then(data => {
        if (data.data && data.data.length > 0) setItems(data.data);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  return (
    <>
      {/* Hero */}
      <div
        className="op-hero"
        style={{
          background:
            "linear-gradient(135deg,rgba(6,18,10,.88) 0%,rgba(8,24,14,.65) 60%,rgba(8,24,14,.5) 100%), url('/images/presentationsbannernew.webp') center/cover no-repeat",
        }}
      >
        <div className="op-hero-deco" aria-hidden="true">
          <svg className="deco-leaf-1" viewBox="0 0 200 300" fill="none">
            <path d="M100 10 C160 40 190 120 160 200 C130 280 40 290 20 220 C0 150 40 80 100 10Z" fill="#7abf9e"/>
            <path d="M100 50 C140 70 160 130 140 190 C120 250 60 260 40 200" stroke="#a9d4bc" strokeWidth="1.5" fill="none"/>
          </svg>
          <svg className="deco-leaf-2" viewBox="0 0 200 300" fill="none">
            <path d="M100 10 C160 40 190 120 160 200 C130 280 40 290 20 220 C0 150 40 80 100 10Z" fill="#7abf9e"/>
          </svg>
        </div>
        <div className="container op-hero-inner">
          <nav className="op-breadcrumb op-breadcrumb--sm" aria-label="Breadcrumb">
            <Link href="/" className="op-bc-item">Home</Link>
            <span className="op-bc-sep" aria-hidden="true">/</span>
            <span className="op-bc-item">Insights &amp; Outreach</span>
            <span className="op-bc-sep" aria-hidden="true">/</span>
            <span className="op-bc-item active">Technical Bulletin</span>
          </nav>
          <h1>Technical <em>Bulletin</em></h1>
        </div>
        <div className="op-hero-wave" aria-hidden="true">
          <svg viewBox="0 0 1440 60" preserveAspectRatio="none" fill="#ffffff">
            <path d="M0,40 C360,70 1080,10 1440,40 L1440,60 L0,60Z"/>
          </svg>
        </div>
      </div>

      {/* Grid */}
      <section className="tb-section">
        <div className="container tb-wrap">
          {loading && items === STATIC ? (
            <div className="tb-loading">
              {[1,2,3,4,5,6].map(n => <div key={n} className="tb-skeleton" />)}
            </div>
          ) : (
            <div className="tb-grid">
              {items.map(item => <BulletinCard key={item.id} item={item} />)}
            </div>
          )}
        </div>
      </section>
    </>
  );
}
