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;

  const completedPercent = totalJobs > 0
    ? Math.round((cacheStatus?.completed ?? 0) / totalJobs * 100)
    : 0;

  // Combine all jobs into unified list with type column
  type UnifiedJob = {
    id: string;
    type: 'pypi';
    package: string;
    status: 'pending' | 'in_progress' | 'completed' | 'failed';
    depth: number;
    attempts: number;
    error?: string | null;
    started_at?: string | null;
    failed_at?: string | null;
    version_constraint?: string | null;
  };

  const allJobs: UnifiedJob[] = [
    // Active tasks first
    ...activeTasks.map((t): UnifiedJob => ({
      id: t.id,
      type: 'pypi',
      package: t.package,
      status: 'in_progress',
      depth: t.depth,
      attempts: t.attempts,
      started_at: t.started_at,
      version_constraint: t.version_constraint,
    })),
    // Then failed tasks
    ...failedTasks.map((t): UnifiedJob => ({
      id: t.id,
      type: 'pypi',
      package: t.package,
      status: 'failed',
      depth: t.depth,
      attempts: t.attempts,
      error: t.error,
      failed_at: t.failed_at,
    })),
  ];

  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>}

      {/* Overall Progress Bar */}
      {totalJobs > 0 && (
        <div className="overall-progress">
          <div className="progress-header">
            <span className="progress-label">
              <span className="pulse-indicator"></span>
              Overall Progress
            </span>
            <span className="progress-stats">
              {cacheStatus?.completed ?? 0} / {totalJobs} completed
              {(cacheStatus?.in_progress ?? 0) > 0 && ` · ${cacheStatus?.in_progress} active`}
              {(cacheStatus?.failed ?? 0) > 0 && ` · ${cacheStatus?.failed} failed`}
            </span>
          </div>
          <div className="progress-bar-container">
            <div
              className="progress-bar-fill"
              style={{ width: `${completedPercent}%` }}
            />
            {(cacheStatus?.in_progress ?? 0) > 0 && (
              <div className="progress-bar-active" />
            )}
          </div>
        </div>
      )}

      {/* Unified 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>
            All 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>
        ) : totalJobs === 0 ? (
          <p className="empty-message">No jobs yet. Jobs are created when packages are downloaded through the PyPI proxy.</p>
        ) : allJobs.length === 0 ? (
          <p className="success-text">All {cacheStatus?.completed ?? 0} jobs completed successfully!</p>
        ) : (
          <table className="jobs-table">
            <thead>
              <tr>
                <th>Type</th>
                <th>Package</th>
                <th>Status</th>
                <th>Depth</th>
                <th>Attempts</th>
                <th>Details</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {allJobs.map((job) => {
                return (
                  <tr key={job.id} className={`job-row ${job.status}`}>
                    <td>
                      <span className="type-badge pypi">PyPI</span>
                    </td>
                    <td className="package-name">
                      {job.status === 'in_progress' && <span className="spinner"></span>}
                      {job.package}
                    </td>
                    <td className="status-cell">
                      {job.status === 'in_progress' ? (
                        <span className="status-badge working">Working</span>
                      ) : job.status === 'failed' ? (
                        <span className="status-badge failed">Failed</span>
                      ) : (
                        <span className="status-badge pending">Pending</span>
                      )}
                    </td>
                    <td>{job.depth}</td>
                    <td>{job.attempts}</td>
                    <td className="details-cell">
                      {job.status === 'failed' && job.error && (
                        <span className="error-text" title={job.error}>
                          {job.error.length > 40 ? job.error.substring(0, 40) + '...' : job.error}
                        </span>
                      )}
                      {job.status === 'in_progress' && job.version_constraint && (
                        <span className="version-text">{job.version_constraint}</span>
                      )}
                      {job.status === 'failed' && job.failed_at && (
                        <span className="timestamp">
                          {new Date(job.failed_at).toLocaleTimeString()}
                        </span>
                      )}
                    </td>
                    <td className="actions-cell">
                      {job.status === 'failed' && (
                        <button
                          className="btn btn-sm btn-secondary"
                          onClick={() => handleRetryPackage(job.package)}
                          disabled={retryingPackage === job.package}
                        >
                          {retryingPackage === job.package ? '...' : 'Retry'}
                        </button>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </section>
    </div>
  );
}

export default AdminJobsPage;
