'use client';

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

type LibraryItem =
  | { type: 'category'; id: number; sort_order: number; name: string; slug: string; description: string | null; pdf_count: number }
  | { type: 'pdf'; id: number; sort_order: number; title: string; slug: string; file_url: string; file_size: string | null; created_at: string };

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

const STATIC_ITEMS: LibraryItem[] = [
  { type: 'category', id: 1, sort_order: 0, name: 'Research Papers',       slug: 'research-papers',       description: 'Peer-reviewed scientific publications and research outcomes.', pdf_count: 5  },
  { type: 'category', id: 2, sort_order: 1, name: 'Product Brochures',     slug: 'product-brochures',     description: 'Detailed information on our veterinary product range.',        pdf_count: 8  },
  { type: 'pdf',      id: 10, sort_order: 2, title: 'Annual Report 2024',  slug: 'annual-report-2024',    file_url: '#', file_size: '4.2 MB', created_at: '2024-04-01' },
  { type: 'category', id: 3, sort_order: 3, name: 'Technical Data Sheets', slug: 'technical-data-sheets', description: 'Specifications and technical details for all products.',        pdf_count: 12 },
  { type: 'pdf',      id: 11, sort_order: 4, title: 'Company Profile',     slug: 'company-profile',       file_url: '#', file_size: '2.1 MB', created_at: '2024-01-15' },
  { type: 'category', id: 4, sort_order: 5, name: 'Field Trial Reports',   slug: 'field-trial-reports',   description: 'Results and analysis from field and clinical trials.',          pdf_count: 3  },
];

export default function DownloadPage() {
  const [items, setItems]     = useState<LibraryItem[]>(STATIC_ITEMS);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`${API_BASE}/api/pdf-library`)
      .then(r => r.json())
      .then(data => { if (data.items?.length) setItems(data.items); })
      .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">Knowledge &amp; Impact</span>
            <span className="op-bc-sep" aria-hidden="true">/</span>
            <span className="op-bc-item active">Download</span>
          </nav>
          <h1>Download <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-section">
        <div className="container rc-wrap">

          {loading ? (
            <div className="rc-library-grid">
              {[1,2,3,4,5,6].map(n => <div key={n} className="rc-folder-skeleton" />)}
            </div>
          ) : items.length > 0 ? (
            <div className="rc-library-grid">
              {items.map(item =>
                item.type === 'category' ? (
                  <Link key={`cat-${item.id}`} href={`/download/${item.slug}`} className="rc-folder-card">
                    <div className="rc-folder-icon" aria-hidden="true">
                      <i className="fas fa-folder" />
                    </div>
                    <span className="rc-folder-name">{item.name}</span>
                    {item.description && <span className="rc-folder-desc">{item.description}</span>}
                  </Link>
                ) : (
                  <a key={`pdf-${item.id}`} href={item.file_url} target="_blank" rel="noopener noreferrer" className="rc-folder-card rc-pdf-inline-card">
                    <div className="rc-pdf-icon-wrap" aria-hidden="true">
                      <i className="fas fa-file-alt" />
                    </div>
                    <span className="rc-folder-name">{item.title}</span>
                  </a>
                )
              )}
            </div>
          ) : (
            <div className="rc-empty">
              <i className="fas fa-folder-open" aria-hidden="true" />
              <p>No documents available yet.</p>
            </div>
          )}

        </div>
      </section>
    </>
  );
}
