import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import {
  getPyPICacheStatus,
  getPyPICacheFailedTasks,
  getPyPICacheActiveTasks,
  retryPyPICacheTask,
  retryAllPyPICacheTasks,
} from '../api';
import { PyPICacheStatus, PyPICacheTask, PyPICacheActiveTask } from '../types';
import './AdminJobsPage.css';

function AdminJobsPage() {
  const { user, loading: authLoading } = useAuth();
  const navigate = useNavigate();

  // PyPI cache status
  const [cacheStatus, setCacheStatus] = useState<PyPICacheStatus | null>(null);
  const [failedTasks, setFailedTasks] = useState<PyPICacheTask[]>([]);
  const [activeTasks, setActiveTasks] = useState<PyPICacheActiveTask[]>([]);
  const [loadingStatus, setLoadingStatus] = useState(true);
  const [statusError, setStatusError] = useState<string | null>(null);

  // Action states
  const [retryingPackage, setRetryingPackage] = useState<string | null>(null);
  const [retryingAll, setRetryingAll] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  // Auto-refresh
  const [autoRefresh, setAutoRefresh] = useState(true);

  useEffect(() => {
    if (!authLoading && !user) {
      navigate('/login', { state: { from: '/admin/jobs' } });
    }
  }, [user, authLoading, navigate]);

  const loadData = useCallback(async () => {
    if (!user?.is_admin) return;

    setStatusError(null);
    try {
      const [status, failed, active] = await Promise.all([
        getPyPICacheStatus(),
        getPyPICacheFailedTasks(100),
        getPyPICacheActiveTasks(50),
      ]);
      setCacheStatus(status);
      setFailedTasks(failed);
      setActiveTasks(active);
    } catch (err) {
      setStatusError(err instanceof Error ? err.message : 'Failed to load status');
    } finally {
      setLoadingStatus(false);
    }
  }, [user]);

  useEffect(() => {
    if (user?.is_admin) {
      loadData();
    }
  }, [user, loadData]);

  // Auto-refresh every 5 seconds when enabled
  useEffect(() => {
    if (!autoRefresh || !user?.is_admin) return;

    const interval = setInterval(() => {
      loadData();
    }, 5000);

    return () => clearInterval(interval);
  }, [autoRefresh, user, loadData]);

  useEffect(() => {
    if (successMessage) {
      const timer = setTimeout(() => setSuccessMessage(null), 3000);
      return () => clearTimeout(timer);
    }
  }, [successMessage]);

  async function handleRetryPackage(packageName: string) {
    setRetryingPackage(packageName);
    try {
      const result = await retryPyPICacheTask(packageName);
      setSuccessMessage(result.message);
      await loadData();
    } catch (err) {
      setStatusError(err instanceof Error ? err.message : 'Failed to retry');
    } finally {
      setRetryingPackage(null);
    }
  }

  async function handleRetryAll() {
    if (!window.confirm('Retry all failed tasks? This will re-queue all failed packages.')) {
      return;
    }

    setRetryingAll(true);
    try {
      const result = await retryAllPyPICacheTasks();
      setSuccessMessage(result.message);
      await loadData();
    } catch (err) {
      setStatusError(err instanceof Error ? err.message : 'Failed to retry all');
    } finally {
      setRetryingAll(false);
    }
  }

  if (authLoading) {
    return <div className="admin-jobs-page">Loading...</div>;
  }

  if (!user?.is_admin) {
    return (
      <div className="admin-jobs-page">
        <div className="error-message">Access denied. Admin privileges required.</div>
      </div>
    );
  }

  const totalJobs = cacheStatus
    ? cacheStatus.pending + cacheStatus.in_progress + cacheStatus.completed + cacheStatus.failed
    : 0;

  return (
    <div className="admin-jobs-page">
      <div className="page-header">
        <h1>Background Jobs</h1>
        <div className="header-actions">
          <label className="auto-refresh-toggle">
            <input
              type="checkbox"
              checked={autoRefresh}
              onChange={(e) => setAutoRefresh(e.target.checked)}
            />
            Auto-refresh
          </label>
          <button className="btn btn-secondary" onClick={loadData} disabled={loadingStatus}>
            Refresh
          </button>
        </div>
      </div>

      {successMessage && <div className="success-message">{successMessage}</div>}
      {statusError && <div className="error-message">{statusError}</div>}

      {/* PyPI Cache Jobs Section */}
      <section className="jobs-section">
        <div className="section-header">
          <h2>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
              <polyline points="3.27 6.96 12 12.01 20.73 6.96"/>
              <line x1="12" y1="22.08" x2="12" y2="12"/>
            </svg>
            PyPI Cache Jobs
          </h2>
          {failedTasks.length > 0 && (
            <button
              className="btn btn-primary"
              onClick={handleRetryAll}
              disabled={retryingAll}
            >
              {retryingAll ? 'Retrying...' : `Retry All Failed (${failedTasks.length})`}
            </button>
          )}
        </div>

        {loadingStatus && !cacheStatus ? (
          <p className="loading-text">Loading job status...</p>
        ) : (
          <>
            {/* Status Cards */}
            <div className="status-cards">
              <div className="status-card pending">
                <div className="status-value">{cacheStatus?.pending ?? 0}</div>
                <div className="status-label">Pending</div>
              </div>
              <div className="status-card in-progress">
                <div className="status-value">{cacheStatus?.in_progress ?? 0}</div>
                <div className="status-label">In Progress</div>
              </div>
              <div className="status-card completed">
                <div className="status-value">{cacheStatus?.completed ?? 0}</div>
                <div className="status-label">Completed</div>
              </div>
              <div className="status-card failed">
                <div className="status-value">{cacheStatus?.failed ?? 0}</div>
                <div className="status-label">Failed</div>
              </div>
            </div>

            {totalJobs === 0 ? (
              <p className="empty-message">No cache jobs yet. Jobs are created when packages are downloaded through the PyPI proxy.</p>
            ) : (
              <>
                {/* Active Workers Table */}
                {activeTasks.length > 0 && (
                  <div className="active-workers-section">
                    <h3>
                      <span className="pulse-indicator"></span>
                      Active Workers ({activeTasks.length})
                    </h3>
                    <table className="jobs-table active-table">
                      <thead>
                        <tr>
                          <th>Package</th>
                          <th>Version</th>
                          <th>Depth</th>
                          <th>Attempt</th>
                          <th>Started</th>
                        </tr>
                      </thead>
                      <tbody>
                        {activeTasks.map((task) => (
                          <tr key={task.id} className="active-row">
                            <td className="package-name">{task.package}</td>
                            <td className="version-constraint">
                              {task.version_constraint || '*'}
                            </td>
                            <td>{task.depth}</td>
                            <td>{task.attempts + 1}</td>
                            <td className="timestamp">
                              {task.started_at
                                ? new Date(task.started_at).toLocaleTimeString()
                                : '-'}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}

                {/* Failed Tasks Table */}
                {failedTasks.length > 0 && (
                  <>
                    <h3>Failed Tasks</h3>
                    <table className="jobs-table">
                      <thead>
                        <tr>
                          <th>Package</th>
                          <th>Error</th>
                          <th>Attempts</th>
                          <th>Depth</th>
                          <th>Failed At</th>
                          <th>Actions</th>
                        </tr>
                      </thead>
                      <tbody>
                        {failedTasks.map((task) => (
                          <tr key={task.id}>
                            <td className="package-name">{task.package}</td>
                            <td className="error-cell" title={task.error || ''}>
                              {task.error || 'Unknown error'}
                            </td>
                            <td>{task.attempts}</td>
                            <td>{task.depth}</td>
                            <td className="timestamp">
                              {task.failed_at
                                ? new Date(task.failed_at).toLocaleString()
                                : '-'}
                            </td>
                            <td className="actions-cell">
                              <button
                                className="btn btn-sm btn-secondary"
                                onClick={() => handleRetryPackage(task.package)}
                                disabled={retryingPackage === task.package}
                              >
                                {retryingPackage === task.package ? 'Retrying...' : 'Retry'}
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </>
                )}

                {/* Success message when nothing is pending/in-progress/failed */}
                {failedTasks.length === 0 && activeTasks.length === 0 && cacheStatus?.pending === 0 && (
                  <p className="success-text">All jobs completed successfully.</p>
                )}

                {/* In progress message */}
                {activeTasks.length === 0 && failedTasks.length === 0 && (cacheStatus?.pending ?? 0) > 0 && (
                  <p className="empty-message">Jobs queued for processing...</p>
                )}
              </>
            )}
          </>
        )}
      </section>

      {/* Placeholder for future job types */}
      <section className="jobs-section coming-soon">
        <div className="section-header">
          <h2>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
              <line x1="3" y1="9" x2="21" y2="9"/>
              <line x1="9" y1="21" x2="9" y2="9"/>
            </svg>
            NPM Cache Jobs
            <span className="coming-soon-badge">Coming Soon</span>
          </h2>
        </div>
        <p className="empty-message">NPM proxy support is planned for a future release.</p>
      </section>
    </div>
  );
}

export default AdminJobsPage;
