'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Loader2, CheckCircle, XCircle, ChevronUp, ChevronDown, X } from 'lucide-react';
import api from '@/lib/api';

interface Task {
  id: string;
  type: string;
  status: 'pending' | 'running' | 'completed' | 'failed';
  progress: number;
  message: string;
  error?: string;
  created_at: string;
}

export default function TaskManager() {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [expanded, setExpanded] = useState(false);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    let interval: NodeJS.Timeout;

    async function pollTasks() {
      try {
        const data = await api.getTasks();
        const activeTasks = data.tasks || [];
        setTasks(activeTasks);

        // Auto-show if there are new active tasks
        if (activeTasks.some((t: Task) => t.status === 'running' || t.status === 'pending')) {
          setVisible(true);
        } else if (activeTasks.length === 0) {
          setVisible(false);
        }
      } catch {
        // silently fail polling
      }
    }

    pollTasks();
    interval = setInterval(pollTasks, 2000); // Poll every 2 seconds

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

  if (!visible || tasks.length === 0) return null;

  const runningCount = tasks.filter(t => t.status === 'running' || t.status === 'pending').length;

  return (
    <motion.div
      initial={{ opacity: 0, y: 50 }}
      animate={{ opacity: 1, y: 0 }}
      className="fixed bottom-6 right-6 z-[100] w-80 shadow-2xl rounded-2xl overflow-hidden flex flex-col"
      style={{ backgroundColor: 'var(--color-bg-elevated)', border: '1px solid var(--color-border)' }}
    >
      {/* Header */}
      <button
        onClick={() => setExpanded(!expanded)}
        className="flex items-center justify-between px-4 py-3 border-b transition-colors hover:bg-white/5"
        style={{ borderColor: 'var(--color-border-subtle)', backgroundColor: 'var(--color-bg-secondary)' }}
      >
        <div className="flex items-center gap-2">
          {runningCount > 0 ? (
            <Loader2 className="w-4 h-4 animate-spin" style={{ color: 'var(--color-accent)' }} />
          ) : (
            <CheckCircle className="w-4 h-4" style={{ color: 'var(--color-success)' }} />
          )}
          <span className="text-sm font-medium" style={{ color: 'var(--color-text-primary)' }}>
            {runningCount > 0 ? `${runningCount} active task${runningCount > 1 ? 's' : ''}` : 'All tasks completed'}
          </span>
        </div>
        <div className="flex items-center gap-1">
          {expanded ? <ChevronDown className="w-4 h-4" style={{ color: 'var(--color-text-tertiary)' }} /> : <ChevronUp className="w-4 h-4" style={{ color: 'var(--color-text-tertiary)' }} />}
          <div
            onClick={(e) => { e.stopPropagation(); setVisible(false); }}
            className="p-1 rounded hover:bg-white/10"
          >
            <X className="w-4 h-4" style={{ color: 'var(--color-text-tertiary)' }} />
          </div>
        </div>
      </button>

      {/* Task List */}
      <AnimatePresence>
        {expanded && (
          <motion.div
            initial={{ height: 0 }}
            animate={{ height: 'auto' }}
            exit={{ height: 0 }}
            className="overflow-hidden"
          >
            <div className="max-h-60 overflow-y-auto p-2 space-y-1" style={{ backgroundColor: 'var(--color-bg-primary)' }}>
              {tasks.map(task => (
                <div key={task.id} className="p-3 rounded-xl" style={{ backgroundColor: 'var(--color-bg-elevated)' }}>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-xs font-semibold uppercase tracking-wider" style={{ color: 'var(--color-text-primary)' }}>
                      {task.type}
                    </span>
                    <span className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                      {task.progress}%
                    </span>
                  </div>
                  
                  <div className="h-1.5 w-full rounded-full overflow-hidden mb-2" style={{ backgroundColor: 'var(--color-bg-secondary)' }}>
                    <motion.div
                      className="h-full rounded-full"
                      initial={{ width: 0 }}
                      animate={{ width: `${task.progress}%` }}
                      style={{
                        backgroundColor: task.status === 'failed' ? 'var(--color-danger)' : task.status === 'completed' ? 'var(--color-success)' : 'var(--color-accent)'
                      }}
                    />
                  </div>

                  <div className="flex items-start gap-2">
                    {task.status === 'failed' ? (
                      <XCircle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" style={{ color: 'var(--color-danger)' }} />
                    ) : task.status === 'completed' ? (
                      <CheckCircle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" style={{ color: 'var(--color-success)' }} />
                    ) : (
                      <Loader2 className="w-3.5 h-3.5 mt-0.5 animate-spin flex-shrink-0" style={{ color: 'var(--color-accent)' }} />
                    )}
                    <span className="text-xs leading-snug break-words" style={{ color: 'var(--color-text-secondary)' }}>
                      {task.status === 'failed' ? task.error : task.message}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
}
