'use client';

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

type FileType = 'pdf' | 'ppt';

interface KrItem {
  id: number;
  title: string;
  file_type: FileType;
  file_url: string | null;
}

const TYPE_LABEL: Record<FileType, string> = {
  pdf: 'PDF',
  ppt: 'PPT',
};

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

  useEffect(() => {
    const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost/agrivet_web/backend';
    fetch(`${apiBaseUrl}/api/knowledge-room`)
      .then(r => r.json())
      .then(json => { if (json.success) setItems(json.data); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const pdfs = items.filter(i => i.file_type === 'pdf');
  const ppts = items.filter(i => i.file_type === 'ppt');

  return (
    <>
      {/* Hero */}
      <div
        className="op-hero"
        style={{
          background:
            "linear-gradient(135deg,rgba(6,18,10,.92) 0%,rgba(8,24,14,.75) 60%,rgba(8,24,14,.58) 100%), url('/images/knowledge-room-bg.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" 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">Knowledge Room</span>
          </nav>
          <h1>Knowledge <em>Room</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>

      {/* Main */}
      <section className="kr2-section">
        <div className="container kr2-wrap">

          {loading ? (
            <div className="kr2-skeletons">
              {[1,2,3,4,5,6].map(n => <div key={n} className="kr2-skeleton" />)}
            </div>
          ) : items.length === 0 ? (
            <div className="kr2-empty">
              <i className="fas fa-folder-open" aria-hidden="true" />
              <p>No documents available yet.</p>
            </div>
          ) : (
            <>
              {/* Presentations section */}
              {ppts.length > 0 && (
                <div className="kr2-group">
                  <div className="kr2-group-header">
                    <div className="kr2-group-icon kr2-group-icon--ppt" aria-hidden="true">
                      <i className="fas fa-file-powerpoint" />
                    </div>
                    <div>
                      <h3 className="kr2-group-title">Presentations</h3>
                    </div>
                  </div>
                  <div className="kr2-grid">
                    {ppts.map(item => <KrCard key={item.id} item={item} />)}
                  </div>
                </div>
              )}

              {/* PDF Documents section */}
              {pdfs.length > 0 && (
                <div className="kr2-group kr2-group--pdf">
                  <div className="kr2-grid">
                    {pdfs.map(item => <KrCard key={item.id} item={item} />)}
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </section>
    </>
  );
}

function KrCard({ item }: { item: KrItem }) {
  const label = TYPE_LABEL[item.file_type] ?? 'PDF';
  return (
    <article className={`kr2-card kr2-card--${item.file_type}`}>
      <div className={`kr2-card-icon kr2-card-icon--${item.file_type}`} aria-hidden="true">
        <i className="fas fa-file" />
        <span className="kr2-card-ext">{label}</span>
      </div>
      <h3 className="kr2-card-title">{item.title}</h3>
      {item.file_url ? (
        <a href={item.file_url} download target="_blank" rel="noreferrer" className="kr2-dl-btn">
          <i className="fas fa-download" aria-hidden="true" />
          Download
        </a>
      ) : (
        <span className="kr2-dl-btn kr2-dl-btn--na">
          <i className="fas fa-clock" aria-hidden="true" />
          Coming Soon
        </span>
      )}
    </article>
  );
}
