'use client';

import { useState } from 'react';
import Link from 'next/link';
import { motion } from 'framer-motion';
import { Factory, ArrowLeft, Zap, Brain, Code, Send, Loader2, Copy, Check, Target, GitBranch } from 'lucide-react';
import { VOCAB } from '@/lib/white-label/constants';

interface RoutingResult {
  success: boolean;
  decision: {
    model: string;
    systemPrompt: string;
    contextInjection: string[];
    analysis: {
      taskType: string;
      complexity: string;
      domain: string[];
      confidence: number;
      estimatedTokens: number;
      reasoning: string;
      detectedPatterns: string[];
    };
    metadata: {
      routedAt: string;
      version: string;
      fallbackChain: string[];
    };
  };
  explanation: string;
}

const EXAMPLE_PROMPTS = [
  {
    label: 'Simple UI Component',
    prompt: 'Create a simple button component with hover effects using Tailwind'
  },
  {
    label: 'API with Database',
    prompt: 'Build an API endpoint to fetch users with pagination using Prisma'
  },
  {
    label: 'Complex Auth System',
    prompt: 'Implement a complete authentication system with NextAuth, including role-based access control and session management'
  },
  {
    label: 'Debug Issue',
    prompt: 'Fix the hydration error in my React component that uses useState with new Date()'
  },
  {
    label: 'Optimization',
    prompt: 'Optimize the complex sorting algorithm that processes large datasets with multiple filters'
  }
];

export default function RouterDemoPage() {
  const [prompt, setPrompt] = useState('');
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [result, setResult] = useState<RoutingResult | null>(null);
  const [copied, setCopied] = useState(false);

  const analyzePrompt = async () => {
    if (!prompt.trim()) return;
    
    setIsAnalyzing(true);
    setResult(null);
    
    try {
      const response = await fetch('/api/dark-factory/route', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt })
      });
      
      const data = await response.json();
      setResult(data);
    } catch (error) {
      console.error('Analysis failed:', error);
    } finally {
      setIsAnalyzing(false);
    }
  };

  const copySystemPrompt = () => {
    if (result?.decision.systemPrompt) {
      navigator.clipboard.writeText(result.decision.systemPrompt);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const getComplexityColor = (complexity: string) => {
    switch (complexity) {
      case 'low': return 'text-green-400 bg-green-500/20';
      case 'medium': return 'text-yellow-400 bg-yellow-500/20';
      case 'high': return 'text-red-400 bg-red-500/20';
      default: return 'text-gray-400 bg-gray-500/20';
    }
  };

  return (
    <div className="min-h-screen bg-brand-bg">
      {/* Header */}
      <header className="fixed top-0 left-0 right-0 z-50 border-b border-white/10 bg-black/50 backdrop-blur-xl">
        <div className="max-w-7xl mx-auto px-4 h-16 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-orange-500 to-red-600 flex items-center justify-center">
              <Factory className="w-5 h-5 text-white" />
            </div>
            <span className="text-xl font-bold text-white">{VOCAB.factory}</span>
          </Link>
          <Link href="/dark-factory/app" className="flex items-center gap-2 text-gray-400 hover:text-white transition-colors">
            <ArrowLeft className="w-4 h-4" />
            Back to Dashboard
          </Link>
        </div>
      </header>

      <main className="pt-24 pb-12 px-4">
        <div className="max-w-4xl mx-auto">
          {/* Title */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="text-center mb-12"
          >
            <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-gradient-to-r from-orange-500/20 to-red-500/20 border border-orange-500/30 mb-6">
              <Brain className="w-4 h-4 text-orange-400" />
              <span className="text-sm text-orange-300">Phase 1: RAG-Augmented Routing</span>
            </div>
            <h1 className="text-4xl font-bold text-white mb-4">Intelligent Prompt Router</h1>
            <p className="text-gray-400 text-lg">
              See how {VOCAB.factory} analyzes your prompts and routes them to the optimal LLM
            </p>
          </motion.div>

          {/* Example Prompts */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.1 }}
            className="mb-6"
          >
            <p className="text-sm text-gray-500 mb-3">Try an example:</p>
            <div className="flex flex-wrap gap-2">
              {EXAMPLE_PROMPTS.map((example, i) => (
                <button
                  key={i}
                  onClick={() => setPrompt(example.prompt)}
                  className="px-3 py-1.5 text-sm bg-white/5 border border-white/10 rounded-lg text-gray-300 hover:bg-white/10 hover:border-orange-500/30 transition-all"
                >
                  {example.label}
                </button>
              ))}
            </div>
          </motion.div>

          {/* Input Area */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
            className="glass-card p-6 bg-black/50 mb-8"
          >
            <label className="block text-sm font-medium text-gray-300 mb-3">
              <Code className="w-4 h-4 inline mr-2" />
              Enter your code generation prompt
            </label>
            <textarea
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              placeholder="Describe what you want to build..."
              rows={4}
              className="w-full bg-white/5 border border-white/10 rounded-lg px-4 py-3 text-white placeholder-gray-500 focus:outline-none focus:border-orange-500/50 focus:ring-1 focus:ring-orange-500/50 resize-none"
            />
            <button
              onClick={analyzePrompt}
              disabled={!prompt.trim() || isAnalyzing}
              className="mt-4 w-full py-3 bg-gradient-to-r from-orange-500 to-red-600 rounded-lg font-semibold text-white hover:shadow-lg hover:shadow-orange-500/25 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              {isAnalyzing ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  Analyzing...
                </>
              ) : (
                <>
                  <Send className="w-5 h-5" />
                  Analyze & Route
                </>
              )}
            </button>
          </motion.div>

          {/* Results */}
          {result && result.success && (
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="space-y-6"
            >
              {/* Model Selection */}
              <div className="glass-card p-6 bg-black/50 border-l-4 border-orange-500">
                <div className="flex items-start justify-between mb-4">
                  <div>
                    <h3 className="text-xl font-bold text-white flex items-center gap-2">
                      <Target className="w-5 h-5 text-orange-400" />
                      Selected Model
                    </h3>
                    <p className="text-3xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-orange-400 to-red-400 mt-2">
                      {result.decision.model}
                    </p>
                  </div>
                  <div className="text-right">
                    <div className="text-sm text-gray-400">Confidence</div>
                    <div className="text-2xl font-bold text-green-400">
                      {Math.round(result.decision.analysis.confidence * 100)}%
                    </div>
                  </div>
                </div>
                <p className="text-gray-300">{result.decision.analysis.reasoning}</p>
              </div>

              {/* Analysis Grid */}
              <div className="grid md:grid-cols-2 gap-6">
                {/* Task Analysis */}
                <div className="glass-card p-6 bg-black/50">
                  <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                    <Zap className="w-5 h-5 text-brand" />
                    Task Analysis
                  </h3>
                  <div className="space-y-3">
                    <div className="flex justify-between items-center">
                      <span className="text-gray-400">Task Type</span>
                      <span className="text-white font-medium capitalize">{result.decision.analysis.taskType}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-gray-400">Complexity</span>
                      <span className={`px-2 py-1 rounded text-sm font-medium capitalize ${getComplexityColor(result.decision.analysis.complexity)}`}>
                        {result.decision.analysis.complexity}
                      </span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-gray-400">Est. Tokens</span>
                      <span className="text-white font-medium">~{result.decision.analysis.estimatedTokens.toLocaleString()}</span>
                    </div>
                  </div>
                </div>

                {/* Domains & Patterns */}
                <div className="glass-card p-6 bg-black/50">
                  <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                    <GitBranch className="w-5 h-5 text-brand-secondary-light" />
                    Detected Context
                  </h3>
                  <div className="space-y-4">
                    <div>
                      <span className="text-sm text-gray-400 block mb-2">Domains</span>
                      <div className="flex flex-wrap gap-2">
                        {result.decision.analysis.domain.map((d, i) => (
                          <span key={i} className="px-2 py-1 bg-brand-secondary/20 text-brand-secondary-light rounded text-sm">
                            {d}
                          </span>
                        ))}
                      </div>
                    </div>
                    <div>
                      <span className="text-sm text-gray-400 block mb-2">Patterns</span>
                      <div className="flex flex-wrap gap-2">
                        {result.decision.analysis.detectedPatterns.length > 0 ? (
                          result.decision.analysis.detectedPatterns.map((p, i) => (
                            <span key={i} className="px-2 py-1 bg-brand-deep/20 text-brand-light rounded text-sm">
                              {p}
                            </span>
                          ))
                        ) : (
                          <span className="text-gray-500 text-sm">No specific patterns detected</span>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Fallback Chain */}
              <div className="glass-card p-6 bg-black/50">
                <h3 className="text-lg font-semibold text-white mb-4">Fallback Chain</h3>
                <div className="flex items-center gap-3 flex-wrap">
                  <span className="px-3 py-2 bg-orange-500/20 text-orange-300 rounded-lg font-medium border border-orange-500/30">
                    {result.decision.model}
                  </span>
                  {result.decision.metadata.fallbackChain.map((model, i) => (
                    <>
                      <span key={`arrow-${i}`} className="text-gray-500">→</span>
                      <span key={model} className="px-3 py-2 bg-white/5 text-gray-400 rounded-lg border border-white/10">
                        {model}
                      </span>
                    </>
                  ))}
                </div>
              </div>

              {/* System Prompt Preview */}
              <div className="glass-card p-6 bg-black/50">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-lg font-semibold text-white">Generated System Prompt</h3>
                  <button
                    onClick={copySystemPrompt}
                    className="flex items-center gap-2 px-3 py-1.5 bg-white/10 hover:bg-white/20 rounded-lg text-sm text-gray-300 transition-colors"
                  >
                    {copied ? (
                      <><Check className="w-4 h-4 text-green-400" /> Copied!</>
                    ) : (
                      <><Copy className="w-4 h-4" /> Copy</>
                    )}
                  </button>
                </div>
                <pre className="bg-black/50 rounded-lg p-4 text-sm text-gray-300 overflow-x-auto whitespace-pre-wrap border border-white/10">
                  {result.decision.systemPrompt}
                </pre>
              </div>

              {/* Metadata */}
              <div className="text-center text-sm text-gray-500">
                Router v{result.decision.metadata.version} • Routed at {new Date(result.decision.metadata.routedAt).toLocaleString()}
              </div>
            </motion.div>
          )}
        </div>
      </main>
    </div>
  );
}
