import { useEffect, useState } from 'react';
import { fetchUserAssessments } from '../../api.js';
import { getSessionUserId } from '../../apiConfig.js';
import {
  canUserDownloadAssessmentReport,
  isUserUploadStatusComplete,
  isUserUploadStatusInProgress,
  openUserAssessmentReport
} from './userAssessmentReport.js';
import './UserMyVideosPage.css';

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

  const getUserId = () => getSessionUserId();

  useEffect(() => {
    const userId = getUserId();
    if (!userId) {
      setError('Unable to identify current user.');
      setLoading(false);
      return;
    }

    fetchUserAssessments(userId)
      .then((vids) => setVideos(Array.isArray(vids) ? vids : []))
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    const incoming = String(initialStatusFilter?.status || '').trim().toLowerCase();
    if (!incoming) return;
    if (incoming === 'all') {
      setFilterStatus('all');
      return;
    }
    if (incoming === 'done' || incoming === 'in-progress' || incoming === 'not-started') {
      setFilterStatus(`bucket:${incoming}`);
    }
  }, [initialStatusFilter?.token, initialStatusFilter?.status]);

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

  function matchesBucketStatus(v, bucket) {
    const label = getStatusLabel(v).toLowerCase();
    if (bucket === 'done') return isUserUploadStatusComplete(v);
    if (bucket === 'in-progress') return isUserUploadStatusInProgress(v);
    if (bucket === 'not-started') return label.includes('not started') || Number(v.assessment_status_id) === 1;
    return true;
  }

  const filtered = videos.filter((v) => {
    const matchesSearch =
      !search ||
      (v.video_title || '').toLowerCase().includes(search.toLowerCase()) ||
      ((v.contract_details ?? v.contact_details) || '').toLowerCase().includes(search.toLowerCase()) ||
      (v.remarks || '').toLowerCase().includes(search.toLowerCase());
    const matchesStatus = filterStatus === 'all'
      || (filterStatus.startsWith('bucket:')
        ? matchesBucketStatus(v, filterStatus.replace('bucket:', ''))
        : String(v.assessment_status_id) === filterStatus);
    return matchesSearch && matchesStatus;
  });

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

  function pillClass(v) {
    const label = getStatusLabel(v).toLowerCase();
    if (isUserUploadStatusComplete(v)) return 'status-pill--success';
    if (label.includes('progress') || label.includes('ongoing')) return 'status-pill--info';
    if (label.includes('returned')) return 'status-pill--returned';
    if (label.includes('high') || label.includes('risk')) return 'status-pill--danger';
    return 'status-pill--warning';
  }

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

  function formatDate(val) {
    if (!val) return '--';
    try {
      const d = new Date(val);
      return d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
    } catch {
      return val;
    }
  }

  return (
    <main className="dashboard-main">
      <header className="dashboard-header">
        <div className="dashboard-header-left">
          <h1>My Uploaded Videos</h1>
          <p>View and track all videos you have submitted for assessment.</p>
        </div>
        {typeof onNavigateUpload === 'function' && (
          <div className="dashboard-header-right">
            <button type="button" className="primary-button" onClick={onNavigateUpload}>
              <span>Upload Video</span>
            </button>
          </div>
        )}
      </header>

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

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

      <section className="uv-table-card">
        {loading ? (
          <p style={{ textAlign: 'center', padding: 32, color: 'var(--theme-gray-400)' }}>Loading your videos...</p>
        ) : (
          <>
            <div className="uv-table-wrapper">
              <table className="uv-table">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Video Title</th>
                    <th>Location</th>
                    <th>Work Area</th>
                    <th>Contract Details</th>
                    <th>Capture Date</th>
                    <th>Capture Time</th>
                    <th>Remarks</th>
                    <th>Status</th>
                    <th>Report</th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.length === 0 && (
                    <tr>
                      <td colSpan={10} className="uv-empty">
                        {videos.length === 0 ? 'You have not uploaded any videos yet.' : 'No videos match your filters.'}
                      </td>
                    </tr>
                  )}
                  {filtered.map((v, idx) => (
                    <tr key={v.assessment_id}>
                      <td>{idx + 1}</td>
                      <td className="uv-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>{formatDate(v.video_capture_date)}</td>
                      <td>{v.video_capture_time || '--'}</td>
                      <td className="uv-cell-remarks">{v.remarks || '--'}</td>
                      <td>
                        <span className={`status-pill ${pillClass(v)}`}>
                          {getStatusLabel(v)}
                        </span>
                      </td>
                      <td>
                        {canUserDownloadAssessmentReport(v) ? (
                          <button
                            type="button"
                            className="uv-report-btn"
                            onClick={() =>
                              typeof onDownloadReport === 'function'
                                ? onDownloadReport(v)
                                : openUserAssessmentReport(v)
                            }
                          >
                            Download
                          </button>
                        ) : (
                          <span className="uv-report-muted">--</span>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            <div className="uv-table-footer">
              <span className="uv-table-meta">
                Showing {filtered.length} of {videos.length} video{videos.length !== 1 ? 's' : ''}
              </span>
            </div>
          </>
        )}
      </section>
    </main>
  );
}

export default UserMyVideosPage;
