import { useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';

function statusClass(status) {
  switch (status) {
    case 'complete': return 'status-badge status-complete';
    case 'scripted': return 'status-badge status-scripted';
    default:         return 'status-badge status-draft';
  }
}

export default function VideosPage() {
  const navigate = useNavigate();
  const [videos, setVideos]     = useState([]);
  const [loading, setLoading]   = useState(true);
  const [error, setError]       = useState(null);
  const [showNew, setShowNew]   = useState(false);
  const [newTitle, setNewTitle] = useState('');
  const [creating, setCreating] = useState(false);

  useEffect(() => {
    fetch('/api/videos')
      .then(r => r.json())
      .then(data => setVideos(data.videos || []))
      .catch(err => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  async function createVideo(e) {
    e.preventDefault();
    if (!newTitle.trim()) return;
    setCreating(true);
    try {
      const res = await fetch('/api/videos', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: newTitle.trim() }),
      });
      if (!res.ok) throw new Error('Failed');
      const data = await res.json();
      navigate(`/videos/${data.video.id}/edit`);
    } catch (err) {
      alert(err.message);
    } finally {
      setCreating(false);
    }
  }

  return (
    <div className="page">

      <div className="page-header">
        <span className="page-title">VIDEO LIBRARY</span>
        <button onClick={() => { setShowNew(true); setNewTitle(''); }} className="btn-red">
          + NEW
        </button>
      </div>

      {loading && <p className="muted">LOADING...</p>}
      {error   && <p className="error-text">ERROR: {error}</p>}

      {!loading && !error && (
        <table className="data-table">
          <thead>
            <tr>
              <th className="th">ID</th>
              <th className="th">TITLE</th>
              <th className="th">STATUS</th>
              <th className="th">SLIDES</th>
              <th className="th">ACTIONS</th>
            </tr>
          </thead>
          <tbody>
            {videos.map((v, i) => (
              <tr key={v.id} className={i % 2 === 0 ? 'tr-even' : 'tr-odd'}>
                <td className="td td-id">{v.id.slice(0, 8)}</td>
                <td className="td">
                  <Link to={`/videos/${v.id}/edit`}>{v.title || '???'}</Link>
                  {v.course_code && <span className="td-course">[{v.course_code}]</span>}
                </td>
                <td className="td">
                  <span className={statusClass(v.status)}>
                    {(v.status || 'DRAFT').toUpperCase()}
                  </span>
                </td>
                <td className="td td-count">{v.slide_count ?? 0}</td>
                <td className="td">
                  <Link to={`/videos/${v.id}/edit`} className="action">EDIT</Link>
                  {'  '}
                  <a href={`/api/videos/${v.id}/export`} target="_blank" rel="noreferrer"
                     className="action-muted">JSON</a>
                </td>
              </tr>
            ))}
            {videos.length === 0 && (
              <tr>
                <td colSpan={5} className="td td-id" style={{ padding: '2rem 0.75rem' }}>
                  NO VIDEOS FOUND.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      )}

      {showNew && (
        <div className="overlay" onClick={() => setShowNew(false)}>
          <div className="modal-sm" onClick={e => e.stopPropagation()}>
            <div className="modal-title">NEW PRESENTATION</div>
            <form onSubmit={createVideo}>
              <input
                value={newTitle}
                onChange={e => setNewTitle(e.target.value)}
                placeholder="TITLE..."
                className="modal-input"
                autoFocus
                required
              />
              <div style={{ display: 'flex', gap: 10, marginTop: 16, justifyContent: 'flex-end' }}>
                <button type="button" onClick={() => setShowNew(false)} className="btn-ghost">
                  CANCEL
                </button>
                <button type="submit"
                  disabled={creating || !newTitle.trim()}
                  className="btn-red"
                  style={{ opacity: (creating || !newTitle.trim()) ? 0.4 : 1 }}>
                  {creating ? 'WAIT...' : 'CREATE >'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
