import { useEffect, useMemo, useState } from 'react';
import { fetchOracFormDetailsList } from '../../api.js';
import './AdminBrowseFormsPage.css';

function AdminBrowseFormsPage() {
  const [forms, setForms] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [search, setSearch] = useState('');

  useEffect(() => {
    setLoading(true);
    setError('');
    fetchOracFormDetailsList({ leaf_only: true, with_version: true })
      .then((rows) => setForms(Array.isArray(rows) ? rows : []))
      .catch((e) => setError(e.message || 'Failed to load forms'))
      .finally(() => setLoading(false));
  }, []);

  const filteredForms = useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return forms;
    return forms.filter((f) => {
      const title = String(f.title || '').toLowerCase();
      const desc = String(f.description || '').toLowerCase();
      const formId = String(f.form_id || '');
      return title.includes(q) || desc.includes(q) || formId.includes(q);
    });
  }, [forms, search]);

  return (
    <main className="dashboard-main">
      <header className="dashboard-header">
        <div className="dashboard-header-left">
          <h1>View Forms</h1>
          <p>Browse available ORAC forms and search by title, description, or form id.</p>
        </div>
      </header>

      {error && <div className="umf-error">{error}</div>}

      <div className="umf-toolbar">
        <input
          className="umf-search"
          type="text"
          placeholder="Search forms..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      <section className="umf-table-card">
        {loading ? (
          <p className="umf-loading">Loading forms...</p>
        ) : (
          <>
            <div className="umf-table-wrapper">
              <table className="umf-table">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Form ID</th>
                    <th>Title</th>
                    <th>Description</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredForms.length === 0 && (
                    <tr>
                      <td colSpan={4} className="umf-empty">
                        {forms.length === 0 ? 'No forms found.' : 'No forms match your search.'}
                      </td>
                    </tr>
                  )}
                  {filteredForms.map((f, idx) => (
                    <tr key={f.form_id ?? `${f.title}-${idx}`}>
                      <td>{idx + 1}</td>
                      <td>#{f.form_id ?? '--'}</td>
                      <td className="umf-title">{f.title || '--'}</td>
                      <td className="umf-desc">{f.description || '--'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div className="umf-footer">
              <span>
                Showing {filteredForms.length} of {forms.length} form{forms.length !== 1 ? 's' : ''}
              </span>
            </div>
          </>
        )}
      </section>
    </main>
  );
}

export default AdminBrowseFormsPage;
