'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Sparkles,
  Send,
  Loader2,
  CheckCircle,
  AlertCircle,
  Code,
  Database,
  Layers,
  Zap,
  FolderOpen,
  AlertTriangle,
  Settings2,
  Library,
} from 'lucide-react';
import { VoiceInputButton } from '@/components/ui/voice-input';
import { LanguageDBSelector } from './language-db-selector';
import { ExpertModePanel } from './expert-mode-panel';
import { LLMSelector } from './llm-selector';
import { TemplateLibrary } from './template-library';
import DeploymentTargetSelector from './deployment-target-selector';
import type { DeploymentPlatform } from './deployment-target-selector';
import { AgentPipelineFlow, QualityGateBadge } from './agent-hierarchy-panel';
import {
  TargetLanguage,
  TargetDatabase,
  ExpertModeSpec,
  getLanguageOption,
  getDatabaseOption,
} from '@/lib/dark-factory/types/generation-options';
import { DEFAULT_STAGE_CONFIG, LLMStageConfig } from '@/lib/dark-factory/llm-models';
import type { DFTemplate } from '@/lib/dark-factory/templates';
import { VOCAB } from '@/lib/white-label/constants';

interface GenerationFormProps {
  onComplete: () => void;
  projectId?: string;
  projectName?: string;
}

interface GenerationResult {
  success: boolean;
  taskId?: string;
  status?: string;
  artifactCount?: number;
  stages?: Array<{ name: string; status: string; duration?: number }>;
  error?: string;
  pipeline?: string;
  agents?: string[];
  qualityGate?: { minReviewScore: number; minTestAccuracy: number };
  message?: string;
}

const EXAMPLE_PROMPTS = [
  {
    icon: <Database className="w-4 h-4" />,
    label: 'Customer Orders',
    prompt: 'Create an API endpoint that tracks customer orders with status updates, order items, and shipping information',
  },
  {
    icon: <Layers className="w-4 h-4" />,
    label: 'Task Management',
    prompt: 'Create a task management system with projects, tasks, assignees, due dates, and priority levels',
  },
  {
    icon: <Code className="w-4 h-4" />,
    label: 'Inventory Tracker',
    prompt: 'Create an inventory management API with products, stock levels, suppliers, and low-stock alerts',
  },
];

type FormPhase = 'prompt' | 'expert' | 'result';

export function GenerationForm({ onComplete, projectId, projectName }: GenerationFormProps) {
  const [prompt, setPrompt] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);
  const [isLoadingPreview, setIsLoadingPreview] = useState(false);
  const [result, setResult] = useState<GenerationResult | null>(null);
  const [showExamples, setShowExamples] = useState(true);

  // Language & Database selection
  const [language, setLanguage] = useState<TargetLanguage>('typescript-react');
  const [database, setDatabase] = useState<TargetDatabase>('postgresql');

  // Expert Mode
  const [expertMode, setExpertMode] = useState(false);
  const [phase, setPhase] = useState<FormPhase>('prompt');
  const [expertSpec, setExpertSpec] = useState<ExpertModeSpec | null>(null);

  // Multi-LLM Selection
  const [llmConfig, setLlmConfig] = useState<LLMStageConfig>({ ...DEFAULT_STAGE_CONFIG });

  // Deployment Targets
  const [deploymentTargets, setDeploymentTargets] = useState<DeploymentPlatform[]>(['web']);

  // Template Library
  const [showTemplates, setShowTemplates] = useState(false);
  const [activeTemplate, setActiveTemplate] = useState<DFTemplate | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!prompt.trim() || isGenerating) return;

    setShowExamples(false);

    if (expertMode) {
      await loadExpertPreview();
    } else {
      await runGeneration();
    }
  };

  const loadExpertPreview = async () => {
    setIsLoadingPreview(true);
    try {
      const response = await fetch('/api/dark-factory/expert-preview', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          prompt: prompt.trim(),
          language,
          database,
        }),
      });

      const data = await response.json();

      if (data.success && data.spec) {
        setExpertSpec(data.spec);
        setPhase('expert');
      } else {
        setResult({
          success: false,
          error: data.error || 'Failed to generate architecture preview',
        });
        setPhase('result');
      }
    } catch (error) {
      setResult({
        success: false,
        error: error instanceof Error ? error.message : 'Failed to load preview',
      });
      setPhase('result');
    } finally {
      setIsLoadingPreview(false);
    }
  };

  const runGeneration = async (spec?: ExpertModeSpec) => {
    setIsGenerating(true);
    setResult(null);

    try {
      const body: Record<string, unknown> = {
        prompt: prompt.trim(),
        projectId,
        priority: 'normal',
        requestedBy: 'human',
        language,
        database,
        llmConfig,
        deploymentTargets,
      };

      if (spec) {
        body.expertSpec = spec;
      }

      const response = await fetch('/api/dark-factory/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });

      const data = await response.json();
      setResult(data);
      setPhase('result');

      if (data.success) {
        setTimeout(() => {
          onComplete();
        }, 2000);
      }
    } catch (error) {
      setResult({
        success: false,
        error: error instanceof Error ? error.message : 'Generation failed',
      });
      setPhase('result');
    } finally {
      setIsGenerating(false);
    }
  };

  const handleTemplateSelect = (template: DFTemplate) => {
    setPrompt(template.prompt);
    setActiveTemplate(template);
    setShowExamples(false);

    // Apply template suggestions
    if (template.suggestedLanguage) {
      setLanguage(template.suggestedLanguage as TargetLanguage);
    }
    if (template.suggestedDatabase) {
      setDatabase(template.suggestedDatabase as TargetDatabase);
    }

    // If template has expert spec, enable expert mode
    if (template.expertSpec) {
      setExpertMode(true);
      // Pre-populate expert spec for direct editing
      setExpertSpec({
        entities: template.expertSpec.entities,
        endpoints: template.expertSpec.endpoints,
        namingConventions: {
          modelCase: 'PascalCase',
          fieldCase: 'camelCase',
          endpointCase: 'kebab-case',
          fileNaming: 'kebab-case',
        },
        summary: template.description,
      });
    }
  };

  const handleExampleClick = (examplePrompt: string) => {
    setPrompt(examplePrompt);
    setShowExamples(false);
    setActiveTemplate(null);
  };

  const resetForm = () => {
    setPrompt('');
    setResult(null);
    setShowExamples(true);
    setPhase('prompt');
    setExpertSpec(null);
    setActiveTemplate(null);
  };

  // Expert Mode Phase
  if (phase === 'expert' && expertSpec) {
    return (
      <ExpertModePanel
        spec={expertSpec}
        language={language}
        database={database}
        onSpecChange={setExpertSpec}
        onConfirm={() => runGeneration(expertSpec)}
        onBack={() => setPhase('prompt')}
        isGenerating={isGenerating}
      />
    );
  }

  return (
    <div>
      {/* Template Library Modal */}
      <AnimatePresence>
        {showTemplates && (
          <TemplateLibrary
            onSelectTemplate={handleTemplateSelect}
            onClose={() => setShowTemplates(false)}
          />
        )}
      </AnimatePresence>

      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <Sparkles className="w-6 h-6 text-brand" />
          <h2 className="text-xl font-semibold text-white">Generate Code</h2>
        </div>
        <div className="flex items-center gap-2">
          {projectName && (
            <div className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-brand-deep/10 border border-brand-deep/30">
              <FolderOpen className="w-4 h-4 text-brand" />
              <span className="text-sm text-brand-light">{projectName}</span>
            </div>
          )}
        </div>
      </div>

      <p className="text-gray-400 mb-6">
        Describe what you want to build in natural language, or start from a template.
        Choose your target language, database, and LLM models, then let the {VOCAB.factory} handle the rest.
      </p>

      {/* Controls Row: Language/DB + Expert + LLM + Templates */}
      <div className="flex flex-wrap items-center gap-3 mb-6">
        <LanguageDBSelector
          language={language}
          database={database}
          onLanguageChange={setLanguage}
          onDatabaseChange={setDatabase}
          disabled={isGenerating || isLoadingPreview}
        />

        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => setExpertMode(!expertMode)}
            disabled={isGenerating || isLoadingPreview}
            className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-all border ${
              expertMode
                ? 'bg-orange-500/15 border-orange-500/40 text-orange-400'
                : 'bg-white/5 border-white/10 text-gray-400 hover:text-white hover:border-white/20'
            } disabled:opacity-50 disabled:cursor-not-allowed`}
          >
            <Settings2 className="w-4 h-4" />
            Expert
            {expertMode && <CheckCircle className="w-3.5 h-3.5" />}
          </button>

          <LLMSelector
            config={llmConfig}
            onChange={setLlmConfig}
            disabled={isGenerating || isLoadingPreview}
          />

          <button
            type="button"
            onClick={() => setShowTemplates(true)}
            disabled={isGenerating || isLoadingPreview}
            className="flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-all border bg-white/5 border-white/10 text-gray-400 hover:text-white hover:border-white/20 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Library className="w-4 h-4" />
            <span className="hidden sm:inline">Templates</span>
          </button>
        </div>
      </div>

      {/* Active template indicator */}
      {activeTemplate && (
        <div className="flex items-center gap-2 mb-4 px-3 py-2 rounded-lg bg-brand-deep/10 border border-brand-deep/30 text-sm">
          <span className="text-lg">{activeTemplate.icon}</span>
          <span className="text-brand-light">Template: {activeTemplate.name}</span>
          <button
            onClick={() => { setActiveTemplate(null); resetForm(); }}
            className="ml-auto text-gray-400 hover:text-white"
          >
            ×
          </button>
        </div>
      )}

      {/* Deployment Targets */}
      <div className="mb-4">
        <DeploymentTargetSelector
          selected={deploymentTargets}
          onChange={setDeploymentTargets}
        />
      </div>

      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-gray-300 mb-2">
            What do you want to build?
          </label>
          <div className="relative">
            <textarea
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              placeholder="e.g., Create an API that tracks customer orders with status updates, shipping info, and order history..."
              rows={4}
              className="w-full px-4 py-3 pr-14 rounded-xl bg-white/5 border border-white/10 text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-brand-deep/50 focus:border-brand-deep/50 resize-none"
              disabled={isGenerating || isLoadingPreview}
            />
            <div className="absolute top-3 right-3">
              <VoiceInputButton
                onTranscript={(text) => setPrompt(prev => prev + (prev ? ' ' : '') + text)}
                disabled={isGenerating || isLoadingPreview}
              />
            </div>
          </div>
        </div>

        {/* Selected config summary */}
        {prompt.trim() && (
          <div className="flex flex-wrap items-center gap-2 text-xs text-gray-500">
            <span>Target:</span>
            <span className="px-2 py-0.5 rounded bg-brand-deep/10 text-brand">
              {getLanguageOption(language).shortLabel}
            </span>
            <span>+</span>
            <span className="px-2 py-0.5 rounded bg-brand-secondary/10 text-brand-secondary-light">
              {getDatabaseOption(database).shortLabel}
            </span>
            {expertMode && (
              <span className="px-2 py-0.5 rounded bg-orange-500/10 text-orange-400">
                Expert Preview
              </span>
            )}
            {JSON.stringify(llmConfig) !== JSON.stringify(DEFAULT_STAGE_CONFIG) && (
              <span className="px-2 py-0.5 rounded bg-brand-secondary/10 text-brand-secondary-light">
                Custom LLM
              </span>
            )}
            {deploymentTargets.length > 1 && (
              <span className="px-2 py-0.5 rounded bg-green-500/10 text-green-400">
                {deploymentTargets.length} Platforms
              </span>
            )}
          </div>
        )}

        <div className="flex items-center gap-4">
          <button
            type="submit"
            disabled={!prompt.trim() || isGenerating || isLoadingPreview}
            className="flex items-center gap-2 px-6 py-3 rounded-xl font-semibold text-white bg-gradient-to-r from-brand-deep to-brand-secondary hover:from-brand hover:to-brand-secondary-light disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-lg shadow-brand-deep/25"
          >
            {isLoadingPreview ? (
              <>
                <Loader2 className="w-5 h-5 animate-spin" />
                Loading Preview...
              </>
            ) : isGenerating ? (
              <>
                <Loader2 className="w-5 h-5 animate-spin" />
                Generating...
              </>
            ) : expertMode ? (
              <>
                <Settings2 className="w-5 h-5" />
                Preview & Edit
              </>
            ) : (
              <>
                <Zap className="w-5 h-5" />
                Generate
              </>
            )}
          </button>

          {!isGenerating && !isLoadingPreview && prompt && (
            <button
              type="button"
              onClick={resetForm}
              className="px-4 py-3 rounded-xl text-gray-400 hover:text-white hover:bg-white/5 transition-colors"
            >
              Clear
            </button>
          )}
        </div>
      </form>

      {/* Example Prompts */}
      {showExamples && !prompt && phase === 'prompt' && (
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          className="mt-8"
        >
          <h3 className="text-sm font-medium text-gray-400 mb-4">Try an example:</h3>
          <div className="grid gap-3">
            {EXAMPLE_PROMPTS.map((example, index) => (
              <button
                key={index}
                onClick={() => handleExampleClick(example.prompt)}
                className="flex items-start gap-3 p-4 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-left transition-colors group"
              >
                <div className="p-2 rounded-lg bg-gradient-to-br from-brand-secondary/20 to-brand-deep/20 text-brand group-hover:text-brand-light">
                  {example.icon}
                </div>
                <div>
                  <div className="font-medium text-white group-hover:text-brand-light transition-colors">
                    {example.label}
                  </div>
                  <div className="text-sm text-gray-500 mt-1 line-clamp-2">
                    {example.prompt}
                  </div>
                </div>
              </button>
            ))}
          </div>

          {/* Template Library CTA */}
          <button
            onClick={() => setShowTemplates(true)}
            className="mt-4 w-full flex items-center justify-center gap-2 px-4 py-3 rounded-xl bg-gradient-to-r from-brand-deep/10 to-brand-secondary/10 border border-brand-deep/20 text-brand hover:text-brand-light hover:border-brand-deep/40 transition-all"
          >
            <Library className="w-5 h-5" />
            Browse Template Library ({"15"} templates)
          </button>
        </motion.div>
      )}

      {/* Result */}
      {result && (
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          className={`mt-6 p-4 rounded-xl border ${
            result.success
              ? 'bg-green-500/10 border-green-500/30'
              : 'bg-red-500/10 border-red-500/30'
          }`}
        >
          <div className="flex items-start gap-3">
            {result.success ? (
              <CheckCircle className="w-5 h-5 text-green-400 mt-0.5" />
            ) : (
              <AlertCircle className="w-5 h-5 text-red-400 mt-0.5" />
            )}
            <div className="flex-1">
              <div className={`font-medium ${result.success ? 'text-green-400' : 'text-red-400'}`}>
                {result.success ? 'Generation Dispatched' : 'Generation Failed'}
              </div>
              {result.success ? (
                <div className="mt-3 space-y-3">
                  {/* Pipeline info */}
                  {result.pipeline === 'standalone' && (
                    <div className="text-xs text-gray-500 uppercase tracking-wider font-semibold">
                      Standalone Agent Pipeline
                    </div>
                  )}

                  {/* Agent pipeline flow */}
                  {result.agents && result.agents.length > 0 && (
                    <AgentPipelineFlow activeAgent={result.agents[0]} />
                  )}

                  {/* Quality gate requirement */}
                  {result.qualityGate && (
                    <QualityGateBadge />
                  )}

                  {/* Task details */}
                  <div className="space-y-1 text-sm text-gray-400 pt-2 border-t border-white/5">
                    <div>Task ID: <code className="text-brand">{result.taskId}</code></div>
                    <div>Status: <span className="text-yellow-400">{result.status}</span></div>
                    {result.message && (
                      <div className="text-xs text-gray-500 mt-1">{result.message}</div>
                    )}
                  </div>

                  {/* Legacy stages display */}
                  {result.stages && (
                    <div className="mt-2">
                      <div className="font-medium text-gray-300 mb-2 text-sm">Pipeline Stages:</div>
                      <div className="space-y-1">
                        {result.stages.map((stage, i) => (
                          <div key={i} className="flex items-center gap-2">
                            {stage.status === 'completed' ? (
                              <CheckCircle className="w-4 h-4 text-green-400" />
                            ) : stage.status === 'failed' ? (
                              <AlertCircle className="w-4 h-4 text-red-400" />
                            ) : (
                              <Loader2 className="w-4 h-4 text-yellow-400 animate-spin" />
                            )}
                            <span className="text-gray-300 text-sm">{stage.name}</span>
                            {stage.duration && (
                              <span className="text-gray-500 text-xs">({stage.duration}ms)</span>
                            )}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              ) : (
                <div className="mt-2 text-sm text-red-300">
                  {result.error || 'An unexpected error occurred'}
                </div>
              )}
            </div>
          </div>
        </motion.div>
      )}
    </div>
  );
}
