'use client';

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

interface PdfItem {
  id: number;
  title: string;
  file_url: string;
  file_size: string | null;
  created_at: string;
}

interface CategoryDetail {
  id: number;
  name: string;
  slug: string;
  description: string | null;
  pdfs: PdfItem[];
}

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

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

export default function CategoryDetailPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = use(params);

  const [data, setData]       = useState<CategoryDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError]     = useState(false);

  useEffect(() => {
    if (!slug) return;
    fetch(`${API_BASE}/api/pdf-library/${slug}`)
      .then(r => { if (!r.ok) throw new Error(); return r.json(); })
      .then(setData)
      .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="/resource-center" className="op-bc-item">Resource Center</Link>
            <span className="op-bc-sep" aria-hidden="true">/</span>
            <span className="op-bc-item active">{data?.name ?? 'Category'}</span>
          </nav>
          <h1>Resource <em>Center</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>

      <section className="rc-detail-section">
        <div className="container rc-detail-wrap">

          <Link href="/resource-center" className="rc-back-btn">
            <i className="fas fa-arrow-left" aria-hidden="true" /> Back to Resource Center
          </Link>

          {/* Loading */}
          {loading && (
            <div className="rc-detail-skeleton">
              <div className="rc-sk-header" />
              {[1,2,3,4,5].map(n => <div key={n} className="rc-sk-row" />)}
            </div>
          )}

          {/* Error */}
          {error && (
            <div className="rc-empty" style={{ marginTop: '2rem' }}>
              <i className="fas fa-exclamation-circle" aria-hidden="true" />
              <p>Category not found or unavailable.</p>
              <Link href="/resource-center" className="rc-back-btn" style={{ marginTop: '.5rem' }}>
                Back to Resource Center
              </Link>
            </div>
          )}

          {/* Content */}
          {data && (
            <>
              <div className="rc-cat-header">
                <div className="rc-cat-icon-lg" aria-hidden="true">
                  <i className="fas fa-folder" />
                </div>
                <div className="rc-cat-info">
                  <h2>{data.name}</h2>
                  {data.description && <p>{data.description}</p>}
                  <span className="rc-section-badge" style={{ marginTop: '.4rem', display: 'inline-block' }}>
                    {data.pdfs.length} PDF{data.pdfs.length !== 1 ? 's' : ''}
                  </span>
                </div>
              </div>

              {data.pdfs.length > 0 ? (
                <div className="rc-detail-pdf-list">
                  {data.pdfs.map(pdf => (
                    <a key={pdf.id} href={pdf.file_url} target="_blank" rel="noopener noreferrer" className="rc-detail-pdf-card">
                      <div className="rc-pdf-icon-wrap" aria-hidden="true">
                        <i className="fas fa-file-alt" />
                      </div>
                      <div className="rc-pdf-info">
                        <div className="rc-detail-pdf-title">{pdf.title}</div>
                        <div className="rc-detail-pdf-meta">
                          {pdf.file_size && <span>{pdf.file_size}</span>}
                          {pdf.file_size && pdf.created_at && <span className="rc-pdf-dot"> · </span>}
                          {pdf.created_at && <span>{formatDate(pdf.created_at)}</span>}
                        </div>
                      </div>
                      <div className="rc-detail-pdf-arrow">
                        <i className="fas fa-arrow-down" aria-hidden="true" />
                      </div>
                    </a>
                  ))}
                </div>
              ) : (
                <div className="rc-empty">
                  <i className="fas fa-folder-open" aria-hidden="true" />
                  <p>No documents in this category yet.</p>
                </div>
              )}
            </>
          )}
        </div>
      </section>
    </>
  );
}
