'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';

interface BulletinDetail {
  id: number;
  title: string;
  excerpt: string | null;
  body: string | null;
  image_url: string | null;
  published_at: string;
}

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

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

export default function BulletinDetailPage() {
  const params = useParams();
  const slug = params?.slug as string;

  const [item, setItem] = useState<BulletinDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [imgFailed, setImgFailed] = useState(false);

  useEffect(() => {
    if (!slug) return;
    fetch(`${API_BASE}/api/technical-bulletins/${slug}`)
      .then(r => {
        if (!r.ok) throw new Error('Not found');
        return r.json();
      })
      .then(data => setItem(data))
      .catch(() => setError(true))
      .finally(() => setLoading(false));
  }, [slug]);

  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>
            <Link href="/technical-bulletin" className="op-bc-item">Technical Bulletin</Link>
            <span className="op-bc-sep" aria-hidden="true">/</span>
            <span className="op-bc-item active">Article</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>

      {/* Detail content */}
      <section className="tb-detail-section">
        <div className="container tb-detail-wrap">
          <Link href="/technical-bulletin" className="tb-back-btn">
            <i className="fas fa-arrow-left" aria-hidden="true" /> Back to Bulletins
          </Link>

          {loading && (
            <div className="tb-detail-skeleton">
              <div className="tb-sk-img" />
              <div className="tb-sk-line tb-sk-line--title" />
              <div className="tb-sk-line" />
              <div className="tb-sk-line" />
              <div className="tb-sk-line tb-sk-line--short" />
            </div>
          )}

          {error && (
            <div className="tb-detail-error">
              <i className="fas fa-exclamation-circle" />
              <p>Bulletin not found or unavailable.</p>
              <Link href="/technical-bulletin" className="tb-back-btn">Back to list</Link>
            </div>
          )}

          {item && (
            <article className="tb-detail-article">
              {/* Featured image */}
              {item.image_url && !imgFailed ? (
                <div className="tb-detail-img-wrap">
                  <img src={item.image_url} alt={item.title} className="tb-detail-img"
                    onError={() => setImgFailed(true)} />
                </div>
              ) : (
                <div className="tb-detail-img-wrap tb-detail-img-placeholder">
                  <img src="/images/agrivet-logo.webp" alt="" className="tb-placeholder-logo-lg" aria-hidden="true" />
                </div>
              )}

              {/* Meta */}
              <div className="tb-detail-meta">
                <span className="tb-detail-date">
                  <i className="fas fa-calendar-days" aria-hidden="true" />
                  {formatDate(item.published_at)}
                </span>
                <span className="tb-detail-tag">Technical Bulletin</span>
              </div>

              {/* Title */}
              <h1 className="tb-detail-title">{item.title}</h1>

              {/* Body */}
              <div className="tb-detail-body">
                {item.body ? (
                  <div dangerouslySetInnerHTML={{ __html: item.body }} />
                ) : item.excerpt ? (
                  <p>{item.excerpt}</p>
                ) : null}
              </div>
            </article>
          )}
        </div>
      </section>
    </>
  );
}
