'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import Link from 'next/link';
import {
  Brain, Sparkles, Cog, CheckCircle, Clock, AlertTriangle,
  ChevronRight, Factory, Zap, RefreshCw
} from 'lucide-react';
import { VOCAB } from '@/lib/white-label/constants';

interface DarkFactoryTask {
  id: string;
  prompt: string;
  status: 'awaiting_approval' | 'in_progress' | 'completed' | 'failed';
  artifactCount: number;
  projectName?: string;
}

export function GhostPanel() {
  const [tasks, setTasks] = useState<DarkFactoryTask[]>([]);
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({ total: 0, pending: 0, completed: 0 });

  useEffect(() => {
    fetchTasks();
  }, []);

  const fetchTasks = async () => {
    try {
      const res = await fetch('/api/dark-factory/tasks?limit=5');
      if (res.ok) {
        const data = await res.json();
        setTasks(data.tasks || []);
        setStats({
          total: data.tasks?.length || 0,
          pending: data.tasks?.filter((t: DarkFactoryTask) => t.status === 'awaiting_approval').length || 0,
          completed: data.tasks?.filter((t: DarkFactoryTask) => t.status === 'completed').length || 0,
        });
      }
    } catch (error) {
      console.error('Failed to fetch tasks:', error);
    } finally {
      setLoading(false);
    }
  };

  const statusColors = {
    awaiting_approval: 'text-amber-400 bg-amber-500/10 border-amber-500/30',
    in_progress: 'text-brand bg-brand-deep/10 border-brand-deep/30',
    completed: 'text-green-400 bg-green-500/10 border-green-500/30',
    failed: 'text-red-400 bg-red-500/10 border-red-500/30',
  };

  const statusIcons = {
    awaiting_approval: <Clock className="w-3 h-3" />,
    in_progress: <RefreshCw className="w-3 h-3 animate-spin" />,
    completed: <CheckCircle className="w-3 h-3" />,
    failed: <AlertTriangle className="w-3 h-3" />,
  };

  return (
    <div className="glass-card p-6 border border-amber-500/20 h-full">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="relative">
            <Brain className="w-6 h-6 text-amber-400" />
            <Sparkles className="absolute -top-1 -right-1 w-3 h-3 text-brand-secondary-light" />
          </div>
          <h2 className="text-xl font-bold text-white">The Ghost</h2>
        </div>
        <Link
          href="/ghost-control/dark-factory"
          className="flex items-center gap-1 text-brand-secondary-light text-sm hover:text-brand-secondary-light transition-colors"
        >
          <Factory className="w-4 h-4" />
          <span>{VOCAB.factory}</span>
          <ChevronRight className="w-4 h-4" />
        </Link>
      </div>

      {/* Stats Row */}
      <div className="grid grid-cols-3 gap-2 mb-4">
        <div className="text-center p-2 bg-white/5 rounded-lg">
          <div className="text-xl font-bold text-white">{stats.total}</div>
          <div className="text-xs text-gray-500">Tasks</div>
        </div>
        <div className="text-center p-2 bg-white/5 rounded-lg">
          <div className="text-xl font-bold text-amber-400">{stats.pending}</div>
          <div className="text-xs text-gray-500">Pending</div>
        </div>
        <div className="text-center p-2 bg-white/5 rounded-lg">
          <div className="text-xl font-bold text-green-400">{stats.completed}</div>
          <div className="text-xs text-gray-500">Built</div>
        </div>
      </div>

      {/* Recent Tasks */}
      <div className="space-y-2 max-h-48 overflow-y-auto">
        {loading ? (
          <div className="text-center py-4">
            <RefreshCw className="w-5 h-5 text-gray-500 animate-spin mx-auto" />
          </div>
        ) : tasks.length === 0 ? (
          <div className="text-center py-4 text-gray-500 text-sm">
            No active tasks
          </div>
        ) : (
          tasks.slice(0, 4).map((task) => (
            <motion.div
              key={task.id}
              whileHover={{ scale: 1.01 }}
              className="p-2 bg-white/5 rounded-lg border border-white/10 hover:border-amber-500/30 transition-colors"
            >
              <div className="flex items-start justify-between gap-2">
                <p className="text-sm text-white truncate flex-1">
                  {task.prompt.substring(0, 50)}...
                </p>
                <span className={`flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border ${statusColors[task.status]}`}>
                  {statusIcons[task.status]}
                  <span className="hidden sm:inline">{task.status.replace('_', ' ')}</span>
                </span>
              </div>
              {task.artifactCount > 0 && (
                <div className="flex items-center gap-1 mt-1 text-xs text-gray-500">
                  <Cog className="w-3 h-3" />
                  <span>{task.artifactCount} artifacts</span>
                </div>
              )}
            </motion.div>
          ))
        )}
      </div>

      <div className="mt-4 pt-4 border-t border-white/10">
        <Link
          href="/ghost-control/dark-factory"
          className="w-full flex items-center justify-center gap-2 px-4 py-2 bg-gradient-to-r from-brand-secondary/20 to-amber-500/20 text-white rounded-lg hover:from-brand-secondary/30 hover:to-amber-500/30 transition-colors border border-brand-secondary/30"
        >
          <Zap className="w-4 h-4 text-amber-400" />
          <span>Build Something New</span>
        </Link>
      </div>
    </div>
  );
}
