'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import Link from 'next/link';
import { useSession, signOut } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import {
  Factory, Plus, FolderOpen, Clock, CheckCircle, AlertTriangle,
  Play, Settings, LogOut, User, ChevronRight, Sparkles,
  Code, Database, Layout, TestTube, Rocket, Loader2,
  Send, X, Archive, Trash2, RefreshCw, Key, BarChart3, Brain, Zap,
  ClipboardList, FileText
} from 'lucide-react';
import { BRAND, VOCAB } from '@/lib/white-label/constants';
import { AgentHierarchyPanel } from '@/components/dark-factory/agent-hierarchy-panel';
import { LANGUAGE_OPTIONS, DATABASE_OPTIONS, type TargetLanguage, type TargetDatabase } from '@/lib/dark-factory/types/generation-options';

interface Project {
  id: string;
  name: string;
  slug: string;
  description: string | null;
  status: string;
  taskCount: number;
  artifactCount: number;
  lastActivityAt: string;
}

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

export default function DarkFactoryApp() {
  const { data: session, status } = useSession();
  const router = useRouter();
  
  const [projects, setProjects] = useState<Project[]>([]);
  const [recentTasks, setRecentTasks] = useState<Task[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showNewPrompt, setShowNewPrompt] = useState(false);
  const [prompt, setPrompt] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);
  const [selectedLanguage, setSelectedLanguage] = useState<TargetLanguage>('typescript-react');
  const [selectedDatabase, setSelectedDatabase] = useState<TargetDatabase>('postgresql');
  const [showOptions, setShowOptions] = useState(false);
  
  // Stats
  const [stats, setStats] = useState({
    totalGenerations: 0,
    remainingThisMonth: 50,
    successRate: 0,
  });

  // RAG stats
  const [ragStats, setRagStats] = useState<{ version: string; cache: { size: number; totalHits: number; totalSaved: number } } | null>(null);

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/dark-factory/login');
      return;
    }
    
    if (status === 'authenticated') {
      loadData();
    }
  }, [status, router]);

  const loadData = async () => {
    try {
      // Load projects
      const projectsRes = await fetch('/api/dark-factory/projects');
      if (projectsRes.ok) {
        const data = await projectsRes.json();
        setProjects(data.projects || []);
      }
      
      // Load recent tasks
      const tasksRes = await fetch('/api/dark-factory/tasks?limit=5');
      if (tasksRes.ok) {
        const data = await tasksRes.json();
        setRecentTasks(data.tasks || []);
        
        // Calculate stats
        const completed = (data.tasks || []).filter((t: Task) => t.status === 'completed').length;
        const total = (data.tasks || []).length;
        setStats(prev => ({
          ...prev,
          totalGenerations: total,
          successRate: total > 0 ? Math.round((completed / total) * 100) : 0,
        }));
      }
      // Load RAG stats
      try {
        const ragRes = await fetch('/api/dark-factory/rag-stats');
        if (ragRes.ok) {
          const ragData = await ragRes.json();
          setRagStats(ragData);
        }
      } catch { /* RAG stats optional */ }
    } catch (error) {
      console.error('Failed to load data:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleGenerate = async () => {
    if (!prompt.trim()) return;
    
    setIsGenerating(true);
    try {
      const response = await fetch('/api/dark-factory/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt, language: selectedLanguage, database: selectedDatabase }),
      });
      
      if (response.ok) {
        const data = await response.json();
        router.push(`/dark-factory/app/tasks/${data.taskId}`);
      }
    } catch (error) {
      console.error('Generation failed:', error);
    } finally {
      setIsGenerating(false);
      setShowNewPrompt(false);
      setPrompt('');
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'text-green-400 bg-green-500/10';
      case 'processing': return 'text-brand bg-brand-deep/10';
      case 'failed': return 'text-red-400 bg-red-500/10';
      default: return 'text-gray-400 bg-gray-500/10';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'completed': return CheckCircle;
      case 'processing': return RefreshCw;
      case 'failed': return AlertTriangle;
      default: return Clock;
    }
  };

  if (status === 'loading' || isLoading) {
    return (
      <div className="min-h-screen bg-brand-bg flex items-center justify-center">
        <Loader2 className="w-8 h-8 text-brand animate-spin" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-brand-bg">
      {/* Header */}
      <header className="sticky top-0 z-50 bg-brand-bg/90 backdrop-blur-lg border-b border-white/5">
        <div className="max-w-7xl mx-auto px-6 py-4">
          <div className="flex items-center justify-between">
            <Link href="/dark-factory/app" className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-brand-deep to-brand-secondary-deep flex items-center justify-center">
                <Factory className="w-6 h-6 text-white" />
              </div>
              <div>
                <span className="text-lg font-bold text-white">{VOCAB.factory}</span>
                <span className="text-xs text-gray-500 block">Dashboard</span>
              </div>
            </Link>
            
            <div className="flex items-center gap-4">
              <Link
                href="/dark-factory/app/api-keys"
                className="flex items-center gap-2 px-3 py-2 text-gray-400 hover:text-white transition-colors"
              >
                <Key className="w-4 h-4" />
                <span className="hidden sm:inline">API Keys</span>
              </Link>
              
              <div className="flex items-center gap-3 pl-4 border-l border-white/10">
                <div className="text-right hidden sm:block">
                  <div className="text-sm text-white">{session?.user?.name || 'User'}</div>
                  <div className="text-xs text-gray-500">{stats.remainingThisMonth} generations left</div>
                </div>
                <div className="relative group">
                  <button className="w-9 h-9 rounded-full bg-gradient-to-br from-brand-deep to-brand-secondary-deep flex items-center justify-center text-white font-medium">
                    {(session?.user?.name || 'U')[0].toUpperCase()}
                  </button>
                  <div className="absolute right-0 top-full mt-2 w-48 py-2 bg-brand-bg-surface rounded-lg border border-white/10 shadow-xl opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all">
                    <Link href="/dark-factory/app/settings" className="flex items-center gap-2 px-4 py-2 text-gray-400 hover:text-white hover:bg-white/5">
                      <Settings className="w-4 h-4" />
                      Settings
                    </Link>
                    <button
                      onClick={() => signOut({ callbackUrl: '/dark-factory' })}
                      className="w-full flex items-center gap-2 px-4 py-2 text-gray-400 hover:text-white hover:bg-white/5"
                    >
                      <LogOut className="w-4 h-4" />
                      Sign Out
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-6 py-8">
        {/* Welcome & Quick Actions */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-white mb-2">
            Welcome back{session?.user?.name ? `, ${session.user.name.split(' ')[0]}` : ''}
          </h1>
          <p className="text-gray-400">What would you like to build today?</p>
        </div>

        {/* Stats Grid */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
          {[
            { label: 'Total Generations', value: stats.totalGenerations, icon: Sparkles },
            { label: 'Remaining This Month', value: stats.remainingThisMonth, icon: BarChart3 },
            { label: 'Success Rate', value: `${stats.successRate}%`, icon: CheckCircle },
            { label: 'Projects', value: projects.length, icon: FolderOpen },
          ].map((stat, i) => (
            <motion.div
              key={i}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: i * 0.1 }}
              className="glass-card p-4 rounded-xl border border-white/5"
            >
              <stat.icon className="w-5 h-5 text-brand mb-2" />
              <div className="text-2xl font-bold text-white">{stat.value}</div>
              <div className="text-sm text-gray-400">{stat.label}</div>
            </motion.div>
          ))}
        </div>

        {/* Quick Generate */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="glass-card p-6 rounded-xl border border-white/10 mb-8"
        >
          <div className="flex items-center gap-3 mb-4">
            <Sparkles className="w-5 h-5 text-brand" />
            <h2 className="text-lg font-semibold text-white">Quick Generate</h2>
          </div>
          
          <div className="flex gap-3">
            <input
              type="text"
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              placeholder="Describe what you want to build..."
              className="flex-1 px-4 py-3 bg-white/5 border border-white/10 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-brand-deep/50"
              onKeyDown={(e) => e.key === 'Enter' && handleGenerate()}
            />
            <button
              onClick={handleGenerate}
              disabled={isGenerating || !prompt.trim()}
              className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-brand-deep to-brand-secondary-deep rounded-lg text-white font-medium hover:opacity-90 transition-opacity disabled:opacity-50"
            >
              {isGenerating ? (
                <Loader2 className="w-5 h-5 animate-spin" />
              ) : (
                <>
                  <Play className="w-5 h-5" />
                  Generate
                </>
              )}
            </button>
          </div>
          
          {/* Language & Database Selectors */}
          <div className="mt-4 flex flex-wrap items-center gap-3">
            <button
              onClick={() => setShowOptions(!showOptions)}
              className="flex items-center gap-2 px-3 py-1.5 text-sm text-gray-400 bg-white/5 rounded-lg hover:bg-white/10 hover:text-white transition-colors border border-white/5"
            >
              <Settings className="w-3.5 h-3.5" />
              <span>{LANGUAGE_OPTIONS.find(l => l.id === selectedLanguage)?.icon} {LANGUAGE_OPTIONS.find(l => l.id === selectedLanguage)?.shortLabel}</span>
              <span className="text-gray-600">|</span>
              <span>{DATABASE_OPTIONS.find(d => d.id === selectedDatabase)?.icon} {DATABASE_OPTIONS.find(d => d.id === selectedDatabase)?.shortLabel}</span>
            </button>

            {showOptions && (
              <div className="w-full flex flex-col sm:flex-row gap-4 p-4 bg-white/5 border border-white/10 rounded-lg animate-in fade-in duration-200">
                <div className="flex-1">
                  <label className="block text-xs text-gray-500 uppercase tracking-wider mb-2">Language / Framework</label>
                  <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
                    {LANGUAGE_OPTIONS.map((lang) => (
                      <button
                        key={lang.id}
                        onClick={() => setSelectedLanguage(lang.id)}
                        className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-all text-left ${
                          selectedLanguage === lang.id
                            ? 'bg-brand-deep/30 border border-brand-deep/50 text-white'
                            : 'bg-white/5 border border-white/5 text-gray-400 hover:bg-white/10 hover:text-white'
                        }`}
                      >
                        <span className="text-lg">{lang.icon}</span>
                        <div>
                          <div className="font-medium">{lang.shortLabel}</div>
                          <div className="text-xs text-gray-500">{lang.framework}</div>
                        </div>
                      </button>
                    ))}
                  </div>
                </div>
                <div className="sm:w-48">
                  <label className="block text-xs text-gray-500 uppercase tracking-wider mb-2">Database</label>
                  <div className="grid grid-cols-2 sm:grid-cols-1 gap-2">
                    {DATABASE_OPTIONS.map((db) => (
                      <button
                        key={db.id}
                        onClick={() => setSelectedDatabase(db.id)}
                        className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-all text-left ${
                          selectedDatabase === db.id
                            ? 'bg-brand-deep/30 border border-brand-deep/50 text-white'
                            : 'bg-white/5 border border-white/5 text-gray-400 hover:bg-white/10 hover:text-white'
                        }`}
                      >
                        <span>{db.icon}</span>
                        <span className="font-medium">{db.shortLabel}</span>
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            )}
          </div>

          <div className="flex flex-wrap gap-2 mt-3">
            {[
              'REST API for orders',
              'User dashboard',
              'Auth system',
              'CRUD endpoints',
            ].map((suggestion) => (
              <button
                key={suggestion}
                onClick={() => setPrompt(suggestion)}
                className="px-3 py-1.5 text-sm text-gray-400 bg-white/5 rounded-full hover:bg-white/10 hover:text-white transition-colors"
              >
                {suggestion}
              </button>
            ))}
          </div>
        </motion.div>

        {/* Agent Hierarchy */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-8"
        >
          <AgentHierarchyPanel />
        </motion.div>

        {/* Prompt Router Demo */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="glass-card p-5 rounded-xl border border-orange-500/20 bg-gradient-to-r from-orange-500/5 to-red-500/5 mb-8"
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Brain className="w-5 h-5 text-orange-400" />
              <div>
                <h3 className="text-sm font-semibold text-white">Intelligent Prompt Router</h3>
                <p className="text-xs text-gray-500">Routes prompts to optimal LLMs</p>
              </div>
            </div>
            <Link
              href="/dark-factory/app/router-demo"
              className="flex items-center gap-2 px-3 py-1.5 text-sm bg-gradient-to-r from-orange-500 to-red-600 rounded-lg text-white font-medium hover:shadow-lg hover:shadow-orange-500/25 transition-all"
            >
              <Zap className="w-3.5 h-3.5" />
              Try Demo
            </Link>
          </div>
        </motion.div>

        {/* RAG Dashboard Widget */}
        {ragStats && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="glass-card p-5 rounded-xl border border-emerald-500/20 bg-gradient-to-r from-emerald-500/5 to-teal-500/5 mb-8"
          >
            <div className="flex items-center gap-3 mb-4">
              <Database className="w-5 h-5 text-emerald-400" />
              <div>
                <h3 className="text-sm font-semibold text-white">RAG Router Intelligence</h3>
                <p className="text-xs text-gray-500">v{ragStats.version} — Token conservation &amp; caching</p>
              </div>
            </div>
            <div className="grid grid-cols-3 gap-3">
              <div className="bg-white/5 rounded-lg p-3 text-center">
                <div className="text-xl font-bold text-emerald-400">{ragStats.cache.size}</div>
                <div className="text-[10px] text-gray-500 uppercase tracking-wider mt-1">Cache Entries</div>
              </div>
              <div className="bg-white/5 rounded-lg p-3 text-center">
                <div className="text-xl font-bold text-teal-400">{ragStats.cache.totalHits}</div>
                <div className="text-[10px] text-gray-500 uppercase tracking-wider mt-1">Cache Hits</div>
              </div>
              <div className="bg-white/5 rounded-lg p-3 text-center">
                <div className="text-xl font-bold text-sky-400">{ragStats.cache.totalSaved.toLocaleString()}</div>
                <div className="text-[10px] text-gray-500 uppercase tracking-wider mt-1">Tokens Saved</div>
              </div>
            </div>
          </motion.div>
        )}

        {/* Intake Pipeline CTA */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="glass-card p-5 rounded-xl border border-sky-500/20 bg-gradient-to-r from-sky-500/5 to-blue-500/5 mb-8"
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <ClipboardList className="w-5 h-5 text-sky-400" />
              <div>
                <h3 className="text-sm font-semibold text-white">Project Intake Pipeline</h3>
                <p className="text-xs text-gray-500">Gate-controlled: Intake → Visuals → Deliverables → Code</p>
              </div>
            </div>
            <Link
              href="/dark-factory/app/intake"
              className="flex items-center gap-2 px-3 py-1.5 text-sm bg-gradient-to-r from-sky-500 to-blue-600 rounded-lg text-white font-medium hover:shadow-lg hover:shadow-sky-500/25 transition-all"
            >
              <FileText className="w-3.5 h-3.5" />
              Open Pipeline
            </Link>
          </div>
        </motion.div>

        {/* Workflow Diagrams CTA */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="glass-card p-5 rounded-xl border border-orange-500/20 bg-gradient-to-r from-orange-500/5 to-pink-500/5 mb-8"
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Code className="w-5 h-5 text-orange-400" />
              <div>
                <h3 className="text-sm font-semibold text-white">Workflow Diagrams</h3>
                <p className="text-xs text-gray-500">Visualize, edit, and export workflow step flows</p>
              </div>
            </div>
            <Link
              href="/dark-factory/app/workflows"
              className="flex items-center gap-2 px-3 py-1.5 text-sm bg-gradient-to-r from-orange-500 to-pink-600 rounded-lg text-white font-medium hover:shadow-lg hover:shadow-orange-500/25 transition-all"
            >
              <Settings className="w-3.5 h-3.5" />
              View Workflows
            </Link>
          </div>
        </motion.div>

        {/* Projects & Tasks Grid */}
        <div className="grid lg:grid-cols-2 gap-8">
          {/* Projects */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
          >
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-white flex items-center gap-2">
                <FolderOpen className="w-5 h-5 text-brand" />
                Projects
              </h2>
              <Link
                href="/dark-factory/app/projects/new"
                className="flex items-center gap-1 text-sm text-brand hover:text-brand-light"
              >
                <Plus className="w-4 h-4" />
                New Project
              </Link>
            </div>
            
            <div className="space-y-3">
              {projects.length === 0 ? (
                <div className="glass-card p-8 rounded-xl border border-white/5 text-center">
                  <FolderOpen className="w-12 h-12 text-gray-600 mx-auto mb-3" />
                  <p className="text-gray-400 mb-4">No projects yet</p>
                  <Link
                    href="/dark-factory/app/projects/new"
                    className="inline-flex items-center gap-2 px-4 py-2 bg-brand-deep/10 border border-brand-deep/20 rounded-lg text-brand hover:bg-brand-deep/20 transition-colors"
                  >
                    <Plus className="w-4 h-4" />
                    Create your first project
                  </Link>
                </div>
              ) : (
                projects.slice(0, 4).map((project) => (
                  <Link
                    key={project.id}
                    href={`/dark-factory/app/projects/${project.id}`}
                    className="block glass-card p-4 rounded-xl border border-white/5 hover:border-brand-deep/30 transition-colors group"
                  >
                    <div className="flex items-center justify-between">
                      <div>
                        <h3 className="text-white font-medium group-hover:text-brand transition-colors">
                          {project.name}
                        </h3>
                        <p className="text-sm text-gray-500">
                          {project.taskCount} tasks • {project.artifactCount} artifacts
                        </p>
                      </div>
                      <ChevronRight className="w-5 h-5 text-gray-600 group-hover:text-brand transition-colors" />
                    </div>
                  </Link>
                ))
              )}
            </div>
          </motion.div>

          {/* Recent Tasks */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.3 }}
          >
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-white flex items-center gap-2">
                <Clock className="w-5 h-5 text-brand-secondary-light" />
                Recent Generations
              </h2>
              <Link
                href="/dark-factory/app/tasks"
                className="text-sm text-brand-secondary-light hover:text-brand-secondary-light"
              >
                View all
              </Link>
            </div>
            
            <div className="space-y-3">
              {recentTasks.length === 0 ? (
                <div className="glass-card p-8 rounded-xl border border-white/5 text-center">
                  <Sparkles className="w-12 h-12 text-gray-600 mx-auto mb-3" />
                  <p className="text-gray-400">No generations yet</p>
                  <p className="text-sm text-gray-500 mt-1">Use Quick Generate above to start</p>
                </div>
              ) : (
                recentTasks.map((task) => {
                  const StatusIcon = getStatusIcon(task.status);
                  return (
                    <Link
                      key={task.id}
                      href={`/dark-factory/app/tasks/${task.id}`}
                      className="block glass-card p-4 rounded-xl border border-white/5 hover:border-brand-secondary/30 transition-colors group"
                    >
                      <div className="flex items-start gap-3">
                        <div className={`p-2 rounded-lg ${getStatusColor(task.status)}`}>
                          <StatusIcon className="w-4 h-4" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <p className="text-white text-sm line-clamp-1 group-hover:text-brand-secondary-light transition-colors">
                            {task.prompt}
                          </p>
                          <p className="text-xs text-gray-500 mt-1">
                            {task.artifactCount} artifacts • {new Date(task.createdAt).toLocaleDateString()}
                          </p>
                        </div>
                      </div>
                    </Link>
                  );
                })
              )}
            </div>
          </motion.div>
        </div>

        {/* FF Integration Notice */}
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.5 }}
          className="mt-12 p-4 rounded-xl bg-gradient-to-r from-brand-deep/5 via-brand-secondary/5 to-brand-deep/5 border border-white/5"
        >
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-brand-deep/20 to-brand-secondary/20 flex items-center justify-center">
              <Factory className="w-5 h-5 text-brand" />
            </div>
            <div className="flex-1">
              <p className="text-sm text-gray-300">
                <span className="text-white font-medium">Part of {BRAND.companyName}</span>
                {' '}— Access the full suite of AI agents and operations tools.
              </p>
            </div>
            <Link
              href="/ghost-control"
              className="text-sm text-brand hover:text-brand-light whitespace-nowrap"
            >
              Go to Control Center →
            </Link>
          </div>
        </motion.div>
      </main>
    </div>
  );
}
