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

/** Prefer API `employee_name`; fall back to user id when name is missing. */
function displayPersonName(name, id) {
  const n = name && String(name).trim();
  if (n) return n;
  if (id != null && id !== '') return String(id);
  return null;
}

function AdminAssignedVideosPage({ onViewVideo }) {
  const [videos, setVideos] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [search, setSearch] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');

  useEffect(() => {
    fetchAssessments()
      .then((all) => {
        // Only show videos that have been assigned (executor or verifier set)
        const assigned = all.filter((v) => v.executor_id || v.verifier_id);
        setVideos(assigned);
      })
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

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

  const filtered = videos.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(videos.map((v) => String(v.assessment_status_id)))];

  function statusLabelForId(statusId) {
    const match = videos.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';
    if (label.includes('return')) return 'status-pill--danger';
    if (label.includes('verif')) 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">Assigned assessments</div>
          <h1>Assigned Videos</h1>
          <p>View details and status of all videos that have been assigned for assessment.</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">{videos.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">
                {videos.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>Location</th>
                    <th>Department</th>
                    <th>Contract Details</th>
                    <th>Capture Date</th>
                    <th>Status</th>
                    <th>Executor</th>
                    <th>Verifier</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.length === 0 && (
                    <tr><td colSpan={10} className="av-empty">No assigned videos found.</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.location_name || '--'}</td>
                      <td>{v.department_name || '--'}</td>
                      <td>{(v.contract_details ?? v.contact_details) || '--'}</td>
                      <td>{v.video_capture_date || '--'}</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={() => onViewVideo?.(v)}
                        >
                          View
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

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

export default AdminAssignedVideosPage;
