import { useEffect, useState } from 'react';
import { fetchAssessments } from '../../api.js';
import './admin-shared.css';
import './AdminAllVideosPage.css';

function displayPersonName(name, id) {
  const n = name && String(name).trim();
  if (n) return n;
  if (id != null && id !== '') return String(id);
  return null;
}

function AdminAllVideosPage({ onAssignVideo }) {
  const [allVideos, setAllVideos] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [search, setSearch] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');

  useEffect(() => {
    fetchAssessments()
      .then((assessments) => setAllVideos(assessments))
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

  const getLabel = (v) => v.assessment_status_name || `Status ${v.assessment_status_id}`;

  const filtered = allVideos.filter((v) => {
    const q = search.toLowerCase();
    const matchesSearch =
      !search ||
      (v.video_title || '').toLowerCase().includes(q) ||
      ((v.contract_details ?? v.contact_details) || '').toLowerCase().includes(q) ||
      (v.executor_name || '').toLowerCase().includes(q) ||
      (v.verifier_name || '').toLowerCase().includes(q) ||
      String(v.executor_id ?? '').includes(search) ||
      String(v.verifier_id ?? '').includes(search);
    const matchesStatus =
      filterStatus === 'all' || String(v.assessment_status_id) === filterStatus;
    return matchesSearch && matchesStatus;
  });

  const statusIds = [...new Set(allVideos.map((v) => String(v.assessment_status_id)))];

  function statusLabelForId(statusId) {
    const match = allVideos.find((v) => String(v.assessment_status_id) === String(statusId));
    return match?.assessment_status_name || `Status ${statusId}`;
  }

  function statusPillClass(v) {
    const label = getLabel(v).toLowerCase();
    if (label.includes('complete') || label.includes('done')) return 'status-pill--success';
    if (label.includes('progress') || label.includes('ongoing')) return 'status-pill--info';
    return 'status-pill--warning';
  }

  return (
    <main className="dashboard-main">
      <header className="admin-page-header admin-page-header--with-actions">
        <div>
          <div className="admin-page-badge">Video management</div>
          <h1>All Videos</h1>
          <p>Browse every uploaded video, review details, and assign team members.</p>
        </div>
      </header>

      {error && <div style={{ color: 'var(--theme-red)', fontSize: 14 }}>{error}</div>}

      <div className="av-filter-bar">
        <div className="av-filter-tabs">
          <button
            type="button"
            className={`av-filter-tab ${filterStatus === 'all' ? 'av-filter-tab--active' : ''}`}
            onClick={() => setFilterStatus('all')}
          >
            All <span className="av-filter-count">{allVideos.length}</span>
          </button>
          {statusIds.map((id) => (
            <button
              key={id}
              type="button"
              className={`av-filter-tab ${filterStatus === id ? 'av-filter-tab--active' : ''}`}
              onClick={() => setFilterStatus(id)}
            >
              {statusLabelForId(id)}
              <span className="av-filter-count">
                {allVideos.filter((v) => String(v.assessment_status_id) === id).length}
              </span>
            </button>
          ))}
        </div>
        <input
          className="admin-table-search"
          type="text"
          placeholder="Search by title, contract details..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      <section className="dashboard-section admin-panel av-table-section">
        {loading ? (
          <p style={{ textAlign: 'center', padding: 24, color: 'var(--theme-gray-400)' }}>Loading...</p>
        ) : (
          <>
            <div className="admin-pending-table-wrapper">
              <table className="admin-pending-table av-table">
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>Video Title</th>
                    <th>Contract Details</th>
                    <th>Capture Date</th>
                    <th>Capture Time</th>
                    <th>Remarks</th>
                    <th>Status</th>
                    <th>Executor</th>
                    <th>Verifier</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.length === 0 && (
                    <tr><td colSpan={10} className="av-empty">No videos match your filters.</td></tr>
                  )}
                  {filtered.map((v) => (
                    <tr key={v.assessment_id}>
                      <td>{v.assessment_id}</td>
                      <td className="av-cell-title">{v.video_title || '—'}</td>
                      <td>{(v.contract_details ?? v.contact_details) || '—'}</td>
                      <td>{v.video_capture_date || '—'}</td>
                      <td>{v.video_capture_time || '—'}</td>
                      <td>{v.remarks || '—'}</td>
                      <td>
                        <span className={`status-pill ${statusPillClass(v)}`}>
                          {getLabel(v)}
                        </span>
                      </td>
                      <td>
                        {displayPersonName(v.executor_name, v.executor_id) ?? (
                          <span className="av-unassigned">—</span>
                        )}
                      </td>
                      <td>
                        {displayPersonName(v.verifier_name, v.verifier_id) ?? (
                          <span className="av-unassigned">—</span>
                        )}
                      </td>
                      <td>
                        <button
                          type="button"
                          className="admin-action-button"
                          onClick={() => onAssignVideo?.(v)}
                        >
                          {v.executor_id ? 'View' : 'Assign'}
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            <div className="av-table-footer">
              <span className="admin-table-meta">
                Showing {filtered.length} of {allVideos.length} videos
              </span>
            </div>
          </>
        )}
      </section>
    </main>
  );
}

export default AdminAllVideosPage;
