'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { ClipboardList, Clock, CheckCircle, AlertTriangle, Loader2, Code, ChevronRight, XCircle } from 'lucide-react';

interface Task {
  id: string;
  status: string;
  prompt: string;
  projectId: string | null;
  project?: { name: string } | null;
  artifactCount: number;
  createdAt: string;
}

const STATUS_CONFIG: Record<string, { label: string; color: string; icon: typeof Clock }> = {
  pending: { label: 'Pending', color: 'text-gray-400 bg-gray-400/10', icon: Clock },
  running: { label: 'Running', color: 'text-sky-400 bg-sky-400/10', icon: Loader2 },
  completed: { label: 'Completed', color: 'text-green-400 bg-green-400/10', icon: CheckCircle },
  failed: { label: 'Failed', color: 'text-red-400 bg-red-400/10', icon: XCircle },
  cancelled: { label: 'Cancelled', color: 'text-gray-500 bg-gray-500/10', icon: AlertTriangle },
};

export default function TasksPage() {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<string>('all');

  useEffect(() => {
    fetch('/api/dark-factory/tasks?limit=50')
      .then(r => r.json())
      .then(data => { setTasks(data.tasks || []); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  const filtered = filter === 'all' ? tasks : tasks.filter(t => t.status === filter);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-2">
            <ClipboardList className="w-6 h-6 text-orange-400" /> Generation Tasks
          </h1>
          <p className="text-gray-400 mt-1">View all code generation tasks and their results</p>
        </div>
        <div className="flex gap-1 bg-white/5 rounded-lg p-1">
          {['all', 'running', 'completed', 'failed'].map(f => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-3 py-1 rounded text-sm capitalize transition-colors ${
                filter === f ? 'bg-sky-500/20 text-sky-400' : 'text-gray-400 hover:text-white'
              }`}
            >
              {f}
            </button>
          ))}
        </div>
      </div>

      {loading ? (
        <div className="text-center py-12 text-gray-500">Loading tasks...</div>
      ) : filtered.length === 0 ? (
        <div className="text-center py-16 border border-dashed border-slate-700 rounded-xl">
          <ClipboardList className="w-12 h-12 text-gray-600 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-400">
            {filter === 'all' ? 'No tasks yet' : `No ${filter} tasks`}
          </h3>
          <p className="text-gray-500 mt-1">Run a generation prompt from the dashboard to create tasks</p>
        </div>
      ) : (
        <div className="space-y-3">
          {filtered.map(task => {
            const cfg = STATUS_CONFIG[task.status] || STATUS_CONFIG.pending;
            const Icon = cfg.icon;
            return (
              <Link
                key={task.id}
                href={`/dark-factory/app/tasks/${task.id}`}
                className="block p-4 bg-white/5 border border-slate-700/50 rounded-xl hover:bg-white/[0.07] transition-colors group"
              >
                <div className="flex items-center justify-between">
                  <div className="space-y-1 min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <span className={`inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full ${cfg.color}`}>
                        <Icon className={`w-3 h-3 ${task.status === 'running' ? 'animate-spin' : ''}`} />
                        {cfg.label}
                      </span>
                      {task.project && (
                        <span className="text-xs text-gray-500">in {task.project.name}</span>
                      )}
                    </div>
                    <p className="text-white truncate">{task.prompt}</p>
                    <div className="flex items-center gap-4 text-xs text-gray-500">
                      <span>{new Date(task.createdAt).toLocaleString()}</span>
                      {task.artifactCount > 0 && (
                        <span className="flex items-center gap-1">
                          <Code className="w-3 h-3" /> {task.artifactCount} artifact{task.artifactCount !== 1 ? 's' : ''}
                        </span>
                      )}
                    </div>
                  </div>
                  <ChevronRight className="w-5 h-5 text-gray-600 group-hover:text-gray-400 transition-colors shrink-0" />
                </div>
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}
