'use client';

import { useState, useEffect, use } from 'react';
import { motion } from 'framer-motion';
import Link from 'next/link';
import {
  ChevronLeft, RefreshCw, Code, FileCode, Database, Layout,
  CheckCircle, Clock, AlertTriangle, Eye, Copy, Download,
  Play, Trash2, Rocket, FileText, Cog, Factory, Loader2
} from 'lucide-react';
import { InternalHeader } from '@/components/ui/internal-header';
import { VOCAB } from '@/lib/white-label/constants';

interface Artifact {
  id: string;
  type: 'component' | 'api' | 'schema' | 'migration' | 'style' | 'test' | 'utility';
  name: string;
  path: string;
  code: string;
  dependencies: string[];
  description: string | null;
  generatedAt: string;
}

interface TaskDetail {
  id: string;
  status: string;
  startedAt: string | null;
  completedAt: string | null;
  error: string | null;
  llmModel: string | null;
  tokensUsed: number | null;
  stages: { name: string; status: string; duration?: number }[];
  createdAt: string;
  request: {
    id: string;
    prompt: string;
    priority: string;
    requestedBy: string;
    projectId: string | null;
    createdAt: string;
  };
  artifacts: Artifact[];
  validations: {
    id: string;
    type: string;
    passed: boolean;
    message: string | null;
  }[];
  deployments: {
    id: string;
    environment: string;
    status: string;
    deployedAt: string | null;
    liveUrl: string | null;
    appSlug: string | null;
  }[];
}

export default function TaskDetailPage({ params }: { params: { taskId: string } | Promise<{ taskId: string }> }) {
  // Handle both sync and async params for Next.js 14.x compatibility
  const resolvedParams = params && typeof (params as Promise<unknown>).then === 'function' 
    ? use(params as Promise<{ taskId: string }>) 
    : params as { taskId: string };
  const taskId = resolvedParams.taskId;
  
  const [task, setTask] = useState<TaskDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedArtifact, setSelectedArtifact] = useState<Artifact | null>(null);
  const [copied, setCopied] = useState(false);
  const [deploying, setDeploying] = useState(false);
  const [deployError, setDeployError] = useState<string | null>(null);
  const [deploySuccess, setDeploySuccess] = useState<{ logs: string[]; artifactCount: number; mode: string } | null>(null);

  useEffect(() => {
    fetchTask();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [taskId]);

  const handleDeploy = async () => {
    if (!task) return;
    setDeploying(true);
    setDeployError(null);
    setDeploySuccess(null);

    try {
      const res = await fetch('/api/dark-factory/deploy', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ taskId: task.id }),
      });

      const data = await res.json();

      if (!res.ok || !data.success) {
        throw new Error(data.error || 'Deployment failed');
      }

      setDeploySuccess({ logs: data.logs || [], artifactCount: data.deployed || 0, mode: data.mode || 'preview' });
      // Refresh task to get updated status
      await fetchTask();
    } catch (err) {
      setDeployError(err instanceof Error ? err.message : 'Deployment failed');
    } finally {
      setDeploying(false);
    }
  };

  const fetchTask = async () => {
    try {
      const res = await fetch(`/api/dark-factory/tasks/${taskId}`);
      if (!res.ok) {
        throw new Error('Task not found');
      }
      const data = await res.json();
      setTask(data.data);
      if (data.data?.artifacts?.length > 0) {
        setSelectedArtifact(data.data.artifacts[0]);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load task');
    } finally {
      setLoading(false);
    }
  };

  const copyCode = () => {
    if (selectedArtifact?.code) {
      navigator.clipboard.writeText(selectedArtifact.code);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const downloadArtifact = () => {
    if (selectedArtifact) {
      const blob = new Blob([selectedArtifact.code], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = selectedArtifact.name;
      a.click();
      URL.revokeObjectURL(url);
    }
  };

  const artifactIcons = {
    component: Layout,
    api: FileCode,
    schema: Database,
    migration: Database,
    style: FileText,
    test: CheckCircle,
    utility: Cog,
  };

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

  if (loading) {
    return (
      <>
        <InternalHeader />
        <div className="min-h-screen bg-brand-bg pt-16 flex items-center justify-center">
          <RefreshCw className="w-8 h-8 text-gray-500 animate-spin" />
        </div>
      </>
    );
  }

  if (error || !task) {
    return (
      <>
        <InternalHeader />
        <div className="min-h-screen bg-brand-bg pt-16">
          <div className="max-w-7xl mx-auto px-4 py-8">
            <div className="glass-card p-12 border border-red-500/30 text-center">
              <AlertTriangle className="w-12 h-12 text-red-400 mx-auto mb-4" />
              <h2 className="text-xl text-white mb-2">Task Not Found</h2>
              <p className="text-gray-500 mb-4">{error}</p>
              <Link
                href="/ghost-control/dark-factory"
                className="inline-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"
              >
                <ChevronLeft className="w-4 h-4" />
                <span>Back to {VOCAB.factory}</span>
              </Link>
            </div>
          </div>
        </div>
      </>
    );
  }

  const statusClass = statusColors[task.status as keyof typeof statusColors] || statusColors.pending;

  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 gap-4 mb-6">
            <Link
              href="/ghost-control/dark-factory"
              className="flex items-center gap-2 text-gray-400 hover:text-white transition-colors"
            >
              <ChevronLeft className="w-5 h-5" />
              <span>{VOCAB.factory}</span>
            </Link>
            <span className="text-gray-600">/</span>
            <span className="text-white">Task Details</span>
          </div>

          {/* Task Info */}
          <div className="glass-card p-6 border border-brand-secondary/20 mb-6">
            <div className="flex items-start justify-between mb-4">
              <div className="flex items-center gap-3">
                <Factory className="w-8 h-8 text-brand-secondary-light" />
                <div>
                  <h1 className="text-2xl font-bold text-white">Generation Task</h1>
                  <p className="text-sm text-gray-500 font-mono">{task.id}</p>
                </div>
              </div>
              <span className={`px-3 py-1.5 rounded-full text-sm ${statusClass}`}>
                {task.status.replace('_', ' ')}
              </span>
            </div>

            <div className="bg-white/5 p-4 rounded-lg mb-4">
              <p className="text-gray-400 text-sm mb-1">Prompt:</p>
              <p className="text-white">{task.request.prompt}</p>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
              <div>
                <p className="text-gray-500">Priority</p>
                <p className="text-white">{task.request.priority}</p>
              </div>
              <div>
                <p className="text-gray-500">Requested By</p>
                <p className="text-white">{task.request.requestedBy}</p>
              </div>
              <div>
                <p className="text-gray-500">Created</p>
                <p className="text-white">{new Date(task.createdAt).toLocaleString()}</p>
              </div>
              <div>
                <p className="text-gray-500">Artifacts</p>
                <p className="text-white">{task.artifacts.length}</p>
              </div>
            </div>

            {task.error && (
              <div className="mt-4 p-4 bg-red-500/10 border border-red-500/30 rounded-lg">
                <p className="text-red-400 text-sm">{task.error}</p>
              </div>
            )}

            {/* Deployment Actions */}
            {task.artifacts.length > 0 && (
              <div className="mt-6 pt-6 border-t border-white/10">
                <div className="flex flex-wrap items-center gap-4">
                  {/* Deploy Button - show for awaiting_approval or completed */}
                  {(task.status === 'awaiting_approval' || task.status === 'completed') && !deploySuccess && (
                    <button
                      onClick={handleDeploy}
                      disabled={deploying}
                      className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-green-500 to-emerald-600 text-white font-semibold rounded-lg hover:from-green-400 hover:to-emerald-500 transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-green-500/25"
                    >
                      {deploying ? (
                        <>
                          <Loader2 className="w-5 h-5 animate-spin" />
                          <span>Deploying...</span>
                        </>
                      ) : (
                        <>
                          <Rocket className="w-5 h-5" />
                          <span>Save &amp; Finalize</span>
                        </>
                      )}
                    </button>
                  )}

                  {/* Status indicator for deployed tasks */}
                  {task.status === 'deployed' && (
                    <span className="flex items-center gap-2 px-4 py-2 bg-green-500/10 text-green-400 rounded-lg border border-green-500/20">
                      <CheckCircle className="w-4 h-4" />
                      <span>Deployed</span>
                    </span>
                  )}
                </div>

                {/* Deploy Error */}
                {deployError && (
                  <div className="mt-4 p-4 bg-red-500/10 border border-red-500/30 rounded-lg">
                    <p className="text-red-400 text-sm">{deployError}</p>
                  </div>
                )}

                {/* Deploy Success */}
                {deploySuccess && (
                  <div className="mt-4 p-4 bg-green-500/10 border border-green-500/30 rounded-lg">
                    <div className="flex items-center gap-2 mb-3">
                      <CheckCircle className="w-5 h-5 text-green-400" />
                      <span className="text-green-400 font-medium">Artifacts Finalized!</span>
                    </div>
                    <p className="text-gray-300 text-sm mb-3">
                      {deploySuccess.artifactCount} artifacts saved. Browse and download the generated code using the artifact viewer above.
                    </p>
                    {deploySuccess.logs.length > 0 && (
                      <details className="mt-2">
                        <summary className="text-gray-500 text-xs cursor-pointer hover:text-gray-400">
                          View logs ({deploySuccess.logs.length} items)
                        </summary>
                        <div className="mt-2 p-2 bg-black/20 rounded text-xs font-mono text-gray-400 max-h-32 overflow-auto">
                          {deploySuccess.logs.map((log, i) => (
                            <div key={i}>{log}</div>
                          ))}
                        </div>
                      </details>
                    )}
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Artifacts Section */}
          {task.artifacts.length > 0 ? (
            <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
              {/* Artifact List */}
              <div className="lg:col-span-1">
                <h3 className="text-lg font-semibold text-white mb-3">Generated Artifacts</h3>
                <div className="space-y-2">
                  {task.artifacts.map((artifact) => {
                    const Icon = artifactIcons[artifact.type as keyof typeof artifactIcons] || Code;
                    return (
                      <button
                        key={artifact.id}
                        onClick={() => setSelectedArtifact(artifact)}
                        className={`w-full p-3 rounded-lg border transition-all text-left ${
                          selectedArtifact?.id === artifact.id
                            ? 'bg-brand-secondary/20 border-brand-secondary/50'
                            : 'bg-white/5 border-white/10 hover:bg-white/10'
                        }`}
                      >
                        <div className="flex items-center gap-2 mb-1">
                          <Icon className="w-4 h-4 text-brand-secondary-light" />
                          <span className="text-white text-sm font-medium truncate">
                            {artifact.name}
                          </span>
                        </div>
                        <p className="text-xs text-gray-500 truncate">{artifact.path}</p>
                        <span className="inline-block mt-1 px-2 py-0.5 text-xs bg-white/10 text-gray-400 rounded">
                          {artifact.type}
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Code Preview */}
              <div className="lg:col-span-3">
                {selectedArtifact && (
                  <div className="glass-card border border-white/10">
                    <div className="flex items-center justify-between p-4 border-b border-white/10">
                      <div>
                        <h4 className="text-white font-medium">{selectedArtifact.name}</h4>
                        <p className="text-sm text-gray-500">{selectedArtifact.path}</p>
                      </div>
                      <div className="flex items-center gap-2">
                        <button
                          onClick={copyCode}
                          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"
                        >
                          {copied ? (
                            <CheckCircle className="w-4 h-4 text-green-400" />
                          ) : (
                            <Copy className="w-4 h-4" />
                          )}
                          <span>{copied ? 'Copied!' : 'Copy'}</span>
                        </button>
                        <button
                          onClick={downloadArtifact}
                          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"
                        >
                          <Download className="w-4 h-4" />
                          <span>Download</span>
                        </button>
                      </div>
                    </div>
                    
                    {selectedArtifact.description && (
                      <div className="px-4 py-3 bg-brand-secondary/10 border-b border-white/10">
                        <p className="text-sm text-brand-secondary-light">{selectedArtifact.description}</p>
                      </div>
                    )}

                    {selectedArtifact.dependencies?.length > 0 && (
                      <div className="px-4 py-2 bg-white/5 border-b border-white/10">
                        <span className="text-xs text-gray-500">Dependencies: </span>
                        {selectedArtifact.dependencies.map((dep, idx) => (
                          <span key={idx} className="text-xs text-brand mr-2">{dep}</span>
                        ))}
                      </div>
                    )}

                    <div className="p-4 overflow-auto max-h-[600px]">
                      <pre className="text-sm text-gray-300 font-mono whitespace-pre-wrap">
                        <code>{selectedArtifact.code}</code>
                      </pre>
                    </div>
                  </div>
                )}
              </div>
            </div>
          ) : (
            <div className="glass-card p-12 border border-white/10 text-center">
              <Code className="w-12 h-12 text-gray-600 mx-auto mb-4" />
              <h3 className="text-xl text-white mb-2">No Artifacts Generated</h3>
              <p className="text-gray-500">This task hasn&apos;t produced any artifacts yet</p>
            </div>
          )}

          {/* Validations & Deployments */}
          {(task.validations.length > 0 || task.deployments.length > 0) && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
              {task.validations.length > 0 && (
                <div className="glass-card p-4 border border-white/10">
                  <h3 className="text-lg font-semibold text-white mb-3">Validations</h3>
                  <div className="space-y-2">
                    {task.validations.map((v) => (
                      <div
                        key={v.id}
                        className={`p-3 rounded-lg border ${
                          v.passed
                            ? 'bg-green-500/10 border-green-500/30'
                            : 'bg-red-500/10 border-red-500/30'
                        }`}
                      >
                        <div className="flex items-center gap-2">
                          {v.passed ? (
                            <CheckCircle className="w-4 h-4 text-green-400" />
                          ) : (
                            <AlertTriangle className="w-4 h-4 text-red-400" />
                          )}
                          <span className={v.passed ? 'text-green-400' : 'text-red-400'}>
                            {v.type}
                          </span>
                        </div>
                        {v.message && (
                          <p className="text-sm text-gray-400 mt-1">{v.message}</p>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {task.deployments.length > 0 && (
                <div className="glass-card p-4 border border-white/10">
                  <h3 className="text-lg font-semibold text-white mb-3">Deployments</h3>
                  <div className="space-y-2">
                    {task.deployments.map((d) => (
                      <div
                        key={d.id}
                        className="p-3 bg-white/5 rounded-lg border border-white/10"
                      >
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            <Rocket className="w-4 h-4 text-brand-secondary-light" />
                            <span className="text-white">{d.environment}</span>
                          </div>
                          <span className={`px-2 py-0.5 text-xs rounded ${
                            d.status === 'deployed'
                              ? 'bg-green-500/20 text-green-400'
                              : d.status === 'pending'
                              ? 'bg-amber-500/20 text-amber-400'
                              : 'bg-gray-500/20 text-gray-400'
                          }`}>
                            {d.status}
                          </span>
                        </div>
                        {d.deployedAt && (
                          <p className="text-xs text-gray-500 mt-1">
                            Deployed: {new Date(d.deployedAt).toLocaleString()}
                          </p>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </>
  );
}