import React, { useState, useEffect } from 'react';
import { Trash2, Download, ExternalLink, RefreshCw } from 'lucide-react';
import { jobsApi } from '../api/client';

const STATUS_COLORS = {
  pending: 'bg-yellow-500',
  downloading: 'bg-blue-500',
  transcribing: 'bg-purple-500',
  translating: 'bg-indigo-500',
  processing: 'bg-orange-500',
  completed: 'bg-green-500',
  failed: 'bg-red-500',
};

const STATUS_LABELS = {
  pending: '대기',
  downloading: '다운로드 중',
  transcribing: '음성 인식',
  translating: '번역',
  processing: '처리 중',
  completed: '완료',
  failed: '실패',
};

export default function JobsPage() {
  const [jobs, setJobs] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  const fetchJobs = async () => {
    setIsLoading(true);
    try {
      const res = await jobsApi.list();
      setJobs(res.data);
    } catch (err) {
      console.error('Failed to fetch jobs:', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchJobs();

    // Auto refresh every 5 seconds
    const interval = setInterval(fetchJobs, 5000);
    return () => clearInterval(interval);
  }, []);

  const handleDelete = async (jobId) => {
    if (!confirm('이 작업을 삭제하시겠습니까?')) return;

    try {
      await jobsApi.delete(jobId);
      setJobs(jobs.filter((j) => j.job_id !== jobId));
    } catch (err) {
      console.error('Failed to delete job:', err);
    }
  };

  const formatDate = (dateStr) => {
    const date = new Date(dateStr);
    return date.toLocaleString('ko-KR', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-2xl font-bold">작업 목록</h2>
        <button
          onClick={fetchJobs}
          className="btn-secondary flex items-center gap-2"
          disabled={isLoading}
        >
          <RefreshCw size={18} className={isLoading ? 'animate-spin' : ''} />
          새로고침
        </button>
      </div>

      {jobs.length === 0 ? (
        <div className="card text-center py-12 text-gray-500">
          <p>아직 작업이 없습니다.</p>
          <p className="text-sm mt-2">새 영상 URL을 입력하여 시작하세요.</p>
        </div>
      ) : (
        <div className="space-y-4">
          {jobs.map((job) => (
            <div key={job.job_id} className="card">
              <div className="flex items-start justify-between gap-4">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-3 mb-2">
                    <span className="font-mono text-sm bg-gray-800 px-2 py-1 rounded">
                      {job.job_id}
                    </span>
                    <span
                      className={`px-2 py-1 rounded text-xs font-medium ${STATUS_COLORS[job.status]} bg-opacity-20`}
                    >
                      <span
                        className={`inline-block w-2 h-2 rounded-full mr-1 ${STATUS_COLORS[job.status]}`}
                      />
                      {STATUS_LABELS[job.status]}
                    </span>
                    <span className="text-sm text-gray-500">
                      {formatDate(job.created_at)}
                    </span>
                  </div>

                  {job.original_url && (
                    <p className="text-sm text-gray-400 truncate mb-2">
                      {job.original_url}
                    </p>
                  )}

                  {job.error && (
                    <p className="text-sm text-red-400 mt-2">
                      오류: {job.error}
                    </p>
                  )}

                  {/* Progress bar */}
                  {!['completed', 'failed'].includes(job.status) && (
                    <div className="mt-3">
                      <div className="h-1 bg-gray-800 rounded-full overflow-hidden">
                        <div
                          className="h-full bg-red-500 transition-all duration-500"
                          style={{ width: `${job.progress}%` }}
                        />
                      </div>
                    </div>
                  )}
                </div>

                <div className="flex items-center gap-2">
                  {job.status === 'completed' && job.output_path && (
                    <a
                      href={jobsApi.downloadOutput(job.job_id)}
                      className="btn-primary flex items-center gap-2"
                      download
                    >
                      <Download size={18} />
                      다운로드
                    </a>
                  )}
                  <button
                    onClick={() => handleDelete(job.job_id)}
                    className="p-2 text-gray-500 hover:text-red-500 transition-colors"
                    title="삭제"
                  >
                    <Trash2 size={18} />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
