'use client';

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

interface PdfCategory {
  id: number;
  name: string;
  slug: string;
  description: string | null;
  pdf_count: number;
}

interface PdfItem {
  id: 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_CATEGORIES: PdfCategory[] = [
  { id: 1, name: 'Research Papers',        slug: 'research-papers',        description: 'Peer-reviewed scientific publications and research outcomes.', pdf_count: 5 },
  { id: 2, name: 'Product Brochures',      slug: 'product-brochures',      description: 'Detailed information on our veterinary product range.',        pdf_count: 8 },
  { id: 3, name: 'Technical Data Sheets',  slug: 'technical-data-sheets',  description: 'Specifications and technical details for all products.',        pdf_count: 12 },
  { id: 4, name: 'Field Trial Reports',    slug: 'field-trial-reports',    description: 'Results and analysis from field and clinical trials.',          pdf_count: 3 },
];

const STATIC_STANDALONE: PdfItem[] = [
  { id: 10, title: 'Annual Report 2024',              slug: 'annual-report-2024',              file_url: '#', file_size: '4.2 MB', created_at: '2024-04-01' },
  { id: 11, title: 'Company Profile',                  slug: 'company-profile',                  file_url: '#', file_size: '2.1 MB', created_at: '2024-01-15' },
  { id: 12, title: 'Sustainability Statement 2023',    slug: 'sustainability-statement-2023',    file_url: '#', file_size: '1.8 MB', created_at: '2023-12-01' },
];

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

export default function ResourceCenterPage() {
  const [categories, setCategories]   = useState<PdfCategory[]>(STATIC_CATEGORIES);
  const [standalone, setStandalone]   = useState<PdfItem[]>(STATIC_STANDALONE);
  const [loading, setLoading]         = useState(true);
  const [query, setQuery]             = useState('');

  useEffect(() => {
    fetch(`${API_BASE}/api/pdf-library`)
      .then(r => r.json())
      .then(data => {
        if (data.categories?.length || data.standalone?.length) {
          if (data.categories?.length) setCategories(data.categories);
          if (data.standalone?.length) setStandalone(data.standalone);
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const q = query.trim().toLowerCase();

  const filteredCategories = useMemo(
    () => q ? categories.filter(c => c.name.toLowerCase().includes(q) || c.description?.toLowerCase().includes(q)) : categories,
    [categories, q]
  );

  const filteredStandalone = useMemo(
    () => q ? standalone.filter(p => p.title.toLowerCase().includes(q)) : standalone,
    [standalone, q]
  );

  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">Resource Center</span>
          </nav>
          <h1>Resource <em>Center</em></h1>
          <p className="op-hero-sub">Download technical documents, research papers, brochures and more.</p>
        </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">

          {/* Search */}
          <div className="rc-search-wrap">
            <div className="rc-search-bar">
              <i className="fas fa-search" aria-hidden="true" />
              <input
                type="search"
                className="rc-search-input"
                placeholder="Search documents, categories…"
                value={query}
                onChange={e => setQuery(e.target.value)}
                aria-label="Search documents"
              />
              {query && (
                <button className="rc-search-clear" onClick={() => setQuery('')} aria-label="Clear search">
                  <i className="fas fa-times" />
                </button>
              )}
            </div>
          </div>

          {/* Categories */}
          {(!q || filteredCategories.length > 0) && (
            <>
              <div className="rc-section-header">
                <i className="fas fa-folder-open rc-section-icon" aria-hidden="true" />
                <h2 className="rc-section-title">Categories</h2>
                {!q && <span className="rc-section-badge">{categories.length}</span>}
              </div>

              {loading ? (
                <div className="rc-folders-grid">
                  {[1,2,3,4].map(n => <div key={n} className="rc-folder-skeleton" />)}
                </div>
              ) : filteredCategories.length > 0 ? (
                <div className="rc-folders-grid">
                  {filteredCategories.map(cat => (
                    <Link key={cat.id} href={`/resource-center/${cat.slug}`} className="rc-folder-card">
                      <div className="rc-folder-icon" aria-hidden="true">
                        <i className="fas fa-folder" />
                      </div>
                      <span className="rc-folder-name">{cat.name}</span>
                      {cat.description && <span className="rc-folder-desc">{cat.description}</span>}
                      <span className="rc-folder-count">{cat.pdf_count} PDF{cat.pdf_count !== 1 ? 's' : ''}</span>
                    </Link>
                  ))}
                </div>
              ) : (
                <div className="rc-empty">
                  <i className="fas fa-folder-open" aria-hidden="true" />
                  <p>No categories match your search.</p>
                </div>
              )}
              <div className="rc-divider" />
            </>
          )}

          {/* Standalone PDFs */}
          {(!q || filteredStandalone.length > 0) && (
            <>
              <div className="rc-section-header">
                <i className="fas fa-file-pdf rc-section-icon rc-section-icon--red" aria-hidden="true" />
                <h2 className="rc-section-title">Documents</h2>
                {!q && <span className="rc-section-badge">{standalone.length}</span>}
              </div>

              {loading ? (
                <div className="rc-pdf-grid">
                  {[1,2,3].map(n => <div key={n} className="rc-pdf-skeleton" />)}
                </div>
              ) : filteredStandalone.length > 0 ? (
                <div className="rc-pdf-grid">
                  {filteredStandalone.map(pdf => (
                    <a key={pdf.id} href={pdf.file_url} target="_blank" rel="noopener noreferrer" className="rc-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-pdf-title">{pdf.title}</div>
                        <div className="rc-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>
                      <i className="fas fa-arrow-down rc-pdf-open" aria-hidden="true" />
                    </a>
                  ))}
                </div>
              ) : (
                <div className="rc-empty">
                  <i className="fas fa-file-pdf" aria-hidden="true" />
                  <p>No documents match your search.</p>
                </div>
              )}
            </>
          )}

          {/* Global empty (search returns nothing at all) */}
          {q && filteredCategories.length === 0 && filteredStandalone.length === 0 && (
            <div className="rc-empty">
              <i className="fas fa-search" aria-hidden="true" />
              <p>No results for <strong>&ldquo;{query}&rdquo;</strong>. Try a different keyword.</p>
            </div>
          )}

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