'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import {
  Factory, Sparkles, Zap, ChevronLeft,
  Plus, CheckCircle, Clock, AlertTriangle, RefreshCw,
  Code, Boxes, Cog, Eye,
  FolderOpen, Loader2, X,
  Crown
} from 'lucide-react';
import { InternalHeader } from '@/components/ui/internal-header';
import { GenerationForm } from '@/components/dark-factory/generation-form';
import { VOCAB } from '@/lib/white-label/constants';

interface DarkFactoryProject {
  id: string;
  name: string;
  slug: string;
  description: string | null;
  businessDomain: string | null;
  status: string;
  color: string;
  taskCount: number;
  artifactCount: number;
  requestCount: number;
  lastActivityAt: string;
  createdAt: string;
}

interface DarkFactoryTask {
  id: string;
  status: 'pending' | 'processing' | 'awaiting_approval' | 'in_progress' | 'completed' | 'failed';
  prompt: string;
  priority: string;
  requestedBy: string;
  projectId: string | null;
  artifactCount: number;
  createdAt: string;
  completedAt: string | null;
  error: string | null;
}

export default function DarkFactoryPage() {
  const [projects, setProjects] = useState<DarkFactoryProject[]>([]);
  const [tasks, setTasks] = useState<DarkFactoryTask[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'create' | 'projects' | 'tasks'>('create');
  
  // Selected project for generation
  const [selectedProject, setSelectedProject] = useState<string>('');
  
  // New project modal
  const [showNewProject, setShowNewProject] = useState(false);
  const [newProjectName, setNewProjectName] = useState('');
  const [newProjectDesc, setNewProjectDesc] = useState('');
  const [newProjectDomain, setNewProjectDomain] = useState('');
  const [newProjectColor, setNewProjectColor] = useState('#0EA5E9');
  const [creatingProject, setCreatingProject] = useState(false);

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

  const fetchData = async () => {
    try {
      const [projectsRes, tasksRes] = await Promise.all([
        fetch('/api/dark-factory/projects'),
        fetch('/api/dark-factory/tasks?limit=50'),
      ]);
      
      if (projectsRes.ok) {
        const pData = await projectsRes.json();
        setProjects(pData.projects || []);
      }
      
      if (tasksRes.ok) {
        const tData = await tasksRes.json();
        setTasks(tData.data || []);
      }
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleGenerationComplete = () => {
    fetchData();
    setActiveTab('tasks');
  };

  const handleCreateProject = async () => {
    if (!newProjectName.trim()) return;
    
    setCreatingProject(true);
    
    try {
      const res = await fetch('/api/dark-factory/projects', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: newProjectName.trim(),
          description: newProjectDesc.trim() || null,
          businessDomain: newProjectDomain.trim() || null,
          color: newProjectColor,
        }),
      });
      
      if (res.ok) {
        const data = await res.json();
        // Add new project to state
        setProjects(prev => [data.project, ...prev]);
        // Auto-select the newly created project
        setSelectedProject(data.project.id);
        // Reset form and close modal
        setShowNewProject(false);
        setNewProjectName('');
        setNewProjectDesc('');
        setNewProjectDomain('');
        setNewProjectColor('#0EA5E9');
        // Refresh the full list to ensure sync
        await fetchData();
      }
    } catch (error) {
      console.error('Failed to create project:', error);
    } finally {
      setCreatingProject(false);
    }
  };

  const statusConfig = {
    pending: { icon: Clock, color: 'text-gray-400', bg: 'bg-gray-500/10', border: 'border-gray-500/30' },
    processing: { icon: RefreshCw, color: 'text-brand', bg: 'bg-brand-deep/10', border: 'border-brand-deep/30' },
    awaiting_approval: { icon: Clock, color: 'text-amber-400', bg: 'bg-amber-500/10', border: 'border-amber-500/30' },
    in_progress: { icon: RefreshCw, color: 'text-brand', bg: 'bg-brand-deep/10', border: 'border-brand-deep/30' },
    completed: { icon: CheckCircle, color: 'text-green-400', bg: 'bg-green-500/10', border: 'border-green-500/30' },
    failed: { icon: AlertTriangle, color: 'text-red-400', bg: 'bg-red-500/10', border: 'border-red-500/30' },
  };

  const colors = ['#0EA5E9', '#FDBA74', '#f59e0b', '#22c55e', '#ef4444', '#ec4899'];

  return (
    <>
      <InternalHeader />
      <div className="min-h-screen bg-brand-bg pt-16">
        <div className="max-w-7xl mx-auto px-4 py-8">
          {/* Header */}
          <div className="flex items-center justify-between mb-8">
            <div className="flex items-center gap-4">
              <Link
                href="/ghost-control"
                className="flex items-center gap-2 text-gray-400 hover:text-white transition-colors"
              >
                <ChevronLeft className="w-5 h-5" />
                <span>Back</span>
              </Link>
              <div className="flex items-center gap-3">
                <div className="relative">
                  <Factory className="w-10 h-10 text-brand-secondary-light" />
                  <Sparkles className="absolute -top-1 -right-1 w-4 h-4 text-amber-400" />
                </div>
                <div>
                  <h1 className="text-3xl font-bold gradient-text">{VOCAB.factory}</h1>
                  <p className="text-gray-400">Build new capabilities with AI</p>
                </div>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <span className="px-3 py-1.5 bg-brand-secondary/10 text-brand-secondary-light text-sm rounded-full border border-brand-secondary/30">
                <Crown className="w-4 h-4 inline-block mr-1" />
                God Mode Feature
              </span>
            </div>
          </div>

          {/* Tab Navigation */}
          <div className="flex gap-2 mb-6">
            {[
              { id: 'create', label: 'Build Something New', icon: Zap },
              { id: 'projects', label: 'Projects', icon: FolderOpen },
              { id: 'tasks', label: 'Generation Tasks', icon: Cog },
            ].map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as 'create' | 'projects' | 'tasks')}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-all ${
                  activeTab === tab.id
                    ? 'bg-brand-secondary/20 text-brand-secondary-light border border-brand-secondary/50'
                    : 'bg-white/5 text-gray-400 border border-white/10 hover:bg-white/10'
                }`}
              >
                <tab.icon className="w-4 h-4" />
                <span>{tab.label}</span>
              </button>
            ))}
          </div>

          {/* Tab Content */}
          <AnimatePresence mode="wait">
            {activeTab === 'create' && (
              <motion.div
                key="create"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                className="space-y-6"
              >
                {/* Project Selection */}
                <div className="glass-card p-6 border border-brand-secondary/30">
                  <label className="block text-sm font-medium text-gray-400 mb-2">
                    Associate with Project (optional)
                  </label>
                  <div className="flex gap-2">
                    <select
                      value={selectedProject}
                      onChange={(e) => setSelectedProject(e.target.value)}
                      className="flex-1 px-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:outline-none focus:border-brand-secondary/50"
                    >
                      <option value="">No project - standalone component</option>
                      {projects.map((p) => (
                        <option key={p.id} value={p.id}>{p.name}</option>
                      ))}
                    </select>
                    <button
                      onClick={() => setShowNewProject(true)}
                      className="px-4 py-2 bg-white/5 border border-white/10 rounded-lg text-gray-400 hover:text-white hover:bg-white/10 transition-colors"
                    >
                      <Plus className="w-5 h-5" />
                    </button>
                  </div>
                </div>

                {/* Generation Form with all features */}
                <div className="glass-card p-6 border border-brand-secondary/30">
                  <GenerationForm
                    onComplete={handleGenerationComplete}
                    projectId={selectedProject || undefined}
                    projectName={projects.find(p => p.id === selectedProject)?.name}
                  />
                </div>
              </motion.div>
            )}

            {activeTab === 'projects' && (
              <motion.div
                key="projects"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
              >
                <div className="flex items-center justify-between mb-6">
                  <h2 className="text-xl font-bold text-white">Your Projects</h2>
                  <button
                    onClick={() => setShowNewProject(true)}
                    className="flex items-center gap-2 px-4 py-2 bg-brand-secondary/20 text-brand-secondary-light rounded-lg hover:bg-brand-secondary/30 transition-colors border border-brand-secondary/30"
                  >
                    <Plus className="w-4 h-4" />
                    <span>New Project</span>
                  </button>
                </div>

                {loading ? (
                  <div className="flex items-center justify-center py-12">
                    <RefreshCw className="w-8 h-8 text-gray-500 animate-spin" />
                  </div>
                ) : projects.length === 0 ? (
                  <div className="glass-card p-12 border border-white/10 text-center">
                    <FolderOpen className="w-12 h-12 text-gray-600 mx-auto mb-4" />
                    <h3 className="text-xl text-white mb-2">No projects yet</h3>
                    <p className="text-gray-500 mb-4">Create a project to organize your generated components</p>
                    <button
                      onClick={() => setShowNewProject(true)}
                      className="px-4 py-2 bg-brand-secondary/20 text-brand-secondary-light rounded-lg hover:bg-brand-secondary/30 transition-colors border border-brand-secondary/30"
                    >
                      Create First Project
                    </button>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {projects.map((project) => (
                      <motion.div
                        key={project.id}
                        whileHover={{ scale: 1.02 }}
                        className="glass-card p-5 border border-white/10 hover:border-brand-secondary/30 transition-all cursor-pointer"
                        style={{ borderLeftColor: project.color, borderLeftWidth: '4px' }}
                      >
                        <div className="flex items-start justify-between mb-3">
                          <h3 className="text-lg font-semibold text-white">{project.name}</h3>
                          <span className={`px-2 py-0.5 text-xs rounded ${
                            project.status === 'active'
                              ? 'bg-green-500/20 text-green-400'
                              : 'bg-gray-500/20 text-gray-400'
                          }`}>
                            {project.status}
                          </span>
                        </div>
                        {project.description && (
                          <p className="text-sm text-gray-400 mb-3 line-clamp-2">{project.description}</p>
                        )}
                        <div className="flex items-center gap-4 text-sm text-gray-500">
                          <span className="flex items-center gap-1">
                            <Cog className="w-4 h-4" />
                            {project.taskCount} tasks
                          </span>
                          <span className="flex items-center gap-1">
                            <Boxes className="w-4 h-4" />
                            {project.artifactCount} artifacts
                          </span>
                        </div>
                        {project.businessDomain && (
                          <div className="mt-3 pt-3 border-t border-white/10">
                            <span className="text-xs text-gray-500">Domain: </span>
                            <span className="text-xs text-brand">{project.businessDomain}</span>
                          </div>
                        )}
                      </motion.div>
                    ))}
                  </div>
                )}
              </motion.div>
            )}

            {activeTab === 'tasks' && (
              <motion.div
                key="tasks"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
              >
                <div className="flex items-center justify-between mb-6">
                  <h2 className="text-xl font-bold text-white">Generation Tasks</h2>
                  <button
                    onClick={fetchData}
                    className="flex items-center gap-2 px-4 py-2 bg-white/5 text-gray-400 rounded-lg hover:bg-white/10 transition-colors border border-white/10"
                  >
                    <RefreshCw className="w-4 h-4" />
                    <span>Refresh</span>
                  </button>
                </div>

                {loading ? (
                  <div className="flex items-center justify-center py-12">
                    <RefreshCw className="w-8 h-8 text-gray-500 animate-spin" />
                  </div>
                ) : tasks.length === 0 ? (
                  <div className="glass-card p-12 border border-white/10 text-center">
                    <Cog className="w-12 h-12 text-gray-600 mx-auto mb-4" />
                    <h3 className="text-xl text-white mb-2">No tasks yet</h3>
                    <p className="text-gray-500">Generate something to see tasks here</p>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {tasks.map((task) => {
                      const config = statusConfig[task.status] || statusConfig.pending;
                      const StatusIcon = config.icon;
                      return (
                        <motion.div
                          key={task.id}
                          whileHover={{ scale: 1.01 }}
                          className={`glass-card p-4 border ${config.border} transition-all`}
                        >
                          <div className="flex items-start justify-between">
                            <div className="flex-1">
                              <div className="flex items-center gap-2 mb-2">
                                <span className={`flex items-center gap-1 px-2 py-0.5 text-xs rounded ${config.bg} ${config.color}`}>
                                  <StatusIcon className={`w-3 h-3 ${task.status === 'in_progress' || task.status === 'processing' ? 'animate-spin' : ''}`} />
                                  {task.status.replace('_', ' ')}
                                </span>
                                <span className="text-xs text-gray-500">
                                  {new Date(task.createdAt).toLocaleString()}
                                </span>
                              </div>
                              <p className="text-white mb-2">{task.prompt}</p>
                              <div className="flex items-center gap-4 text-sm text-gray-500">
                                <span>Priority: {task.priority}</span>
                                <span>Requested by: {task.requestedBy}</span>
                                <span className="flex items-center gap-1">
                                  <Code className="w-4 h-4" />
                                  {task.artifactCount} artifacts
                                </span>
                              </div>
                              {task.error && (
                                <p className="mt-2 text-sm text-red-400">{task.error}</p>
                              )}
                            </div>
                            {task.artifactCount > 0 && (
                              <Link
                                href={`/ghost-control/dark-factory/tasks/${task.id}`}
                                className="flex items-center gap-1 px-3 py-1.5 bg-white/5 text-gray-400 rounded-lg hover:bg-white/10 hover:text-white transition-colors text-sm"
                              >
                                <Eye className="w-4 h-4" />
                                <span>View</span>
                              </Link>
                            )}
                          </div>
                        </motion.div>
                      );
                    })}
                  </div>
                )}
              </motion.div>
            )}
          </AnimatePresence>
        </div>

        {/* New Project Modal */}
        <AnimatePresence>
          {showNewProject && (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4"
              onClick={() => setShowNewProject(false)}
            >
              <motion.div
                initial={{ scale: 0.95, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                exit={{ scale: 0.95, opacity: 0 }}
                onClick={(e) => e.stopPropagation()}
                className="glass-card p-6 border border-brand-secondary/30 max-w-md w-full"
              >
                <div className="flex items-center justify-between mb-6">
                  <h3 className="text-xl font-bold text-white">New Project</h3>
                  <button
                    onClick={() => setShowNewProject(false)}
                    className="text-gray-500 hover:text-white transition-colors"
                  >
                    <X className="w-5 h-5" />
                  </button>
                </div>

                <div className="space-y-4">
                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Project Name *</label>
                    <input
                      type="text"
                      value={newProjectName}
                      onChange={(e) => setNewProjectName(e.target.value)}
                      placeholder="e.g., Customer Portal"
                      className="w-full px-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-brand-secondary/50"
                    />
                  </div>

                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Description</label>
                    <textarea
                      value={newProjectDesc}
                      onChange={(e) => setNewProjectDesc(e.target.value)}
                      placeholder="What is this project for?"
                      rows={3}
                      className="w-full px-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-brand-secondary/50 resize-none"
                    />
                  </div>

                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Business Domain</label>
                    <input
                      type="text"
                      value={newProjectDomain}
                      onChange={(e) => setNewProjectDomain(e.target.value)}
                      placeholder="e.g., E-commerce, Healthcare, Finance"
                      className="w-full px-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-brand-secondary/50"
                    />
                  </div>

                  <div>
                    <label className="block text-sm text-gray-400 mb-2">Color</label>
                    <div className="flex gap-2">
                      {colors.map((color) => (
                        <button
                          key={color}
                          onClick={() => setNewProjectColor(color)}
                          className={`w-8 h-8 rounded-full transition-all ${
                            newProjectColor === color
                              ? 'ring-2 ring-white ring-offset-2 ring-offset-[#0C1222]'
                              : 'hover:scale-110'
                          }`}
                          style={{ backgroundColor: color }}
                        />
                      ))}
                    </div>
                  </div>
                </div>

                <div className="flex gap-3 mt-6">
                  <button
                    onClick={() => setShowNewProject(false)}
                    className="flex-1 px-4 py-2 bg-white/5 text-gray-400 rounded-lg hover:bg-white/10 transition-colors border border-white/10"
                  >
                    Cancel
                  </button>
                  <button
                    onClick={handleCreateProject}
                    disabled={creatingProject || !newProjectName.trim()}
                    className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-brand-secondary/20 text-brand-secondary-light rounded-lg hover:bg-brand-secondary/30 transition-colors border border-brand-secondary/30 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {creatingProject ? (
                      <Loader2 className="w-4 h-4 animate-spin" />
                    ) : (
                      <Plus className="w-4 h-4" />
                    )}
                    <span>Create Project</span>
                  </button>
                </div>
              </motion.div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </>
  );
}