'use client';

/**
 * Dynamic App Page - Renders deployed ${VOCAB.factory} apps
 * Loads app content from the database and renders it
 */

import { useState, useEffect, use } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Bug, RefreshCw, Home, Loader2, AlertTriangle, Code, CheckCircle } from 'lucide-react';
import { InternalHeader } from '@/components/ui/internal-header';
import { VOCAB } from '@/lib/white-label/constants';

interface Artifact {
  id: string;
  fileName: string;
  filePath: string;
  artifactType: string;
  code: string;
  status: string;
}

interface ProjectData {
  project: {
    id: string;
    name: string;
    slug: string;
    description: string;
  };
  artifacts: Artifact[];
  deployedAt?: string;
}

export default function DynamicAppPage() {
  const params = useParams();
  const slug = params?.slug as string;
  
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [projectData, setProjectData] = useState<ProjectData | null>(null);
  const [showFeedback, setShowFeedback] = useState(false);
  const [feedback, setFeedback] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  useEffect(() => {
    if (!slug) return;
    
    async function loadApp() {
      try {
        // Fetch app by slug - checks both project slugs and deployment appSlugs
        const res = await fetch(`/api/dark-factory/apps/${slug}`);
        if (!res.ok) {
          throw new Error('App not found');
        }
        const data = await res.json();
        
        if (!data.found) {
          throw new Error(data.error || 'App not found');
        }
        
        // Transform the response to match expected format
        const artifacts = (data.artifacts || []).map((a: any) => ({
          id: a.id,
          fileName: a.path?.split('/').pop() || a.path || 'unknown',
          filePath: a.path || '',
          artifactType: a.type || 'component',
          code: a.content || '',
          status: a.deployed ? 'deployed' : 'pending',
        }));
        
        setProjectData({
          project: data.project,
          artifacts,
          deployedAt: data.deployment?.deployedAt,
        });
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load app');
      } finally {
        setLoading(false);
      }
    }
    
    loadApp();
  }, [slug]);

  const handleFeedback = async () => {
    if (!feedback.trim()) return;
    setSubmitting(true);
    try {
      await fetch('/api/dark-factory/feedback', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          appSlug: slug,
          feedback: feedback.trim(),
          url: window.location.href,
        }),
      });
      setSubmitted(true);
      setTimeout(() => {
        setShowFeedback(false);
        setFeedback('');
        setSubmitted(false);
      }, 2000);
    } catch (err) {
      console.error('Feedback error:', err);
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-brand-bg flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-12 h-12 text-brand animate-spin mx-auto mb-4" />
          <p className="text-gray-400">Loading {slug}...</p>
        </div>
      </div>
    );
  }

  if (error || !projectData) {
    return (
      <div className="min-h-screen bg-brand-bg">
        <InternalHeader />
        <div className="pt-24 px-6">
          <div className="max-w-2xl mx-auto text-center">
            <AlertTriangle className="w-16 h-16 text-yellow-400 mx-auto mb-6" />
            <h1 className="text-3xl font-bold text-white mb-4">App Not Found</h1>
            <p className="text-gray-400 mb-8">
              The app &quot;{slug}&quot; hasn&apos;t been deployed yet or doesn&apos;t exist.
            </p>
            <div className="flex gap-4 justify-center">
              <Link 
                href="/ghost-control/dark-factory"
                className="px-6 py-3 bg-gradient-to-r from-brand-deep to-brand-secondary text-white rounded-lg hover:opacity-90 transition-opacity flex items-center gap-2"
              >
                <Code className="w-5 h-5" />
                Go to {VOCAB.factory}
              </Link>
              <Link 
                href="/ghost-control"
                className="px-6 py-3 bg-white/10 text-white rounded-lg hover:bg-white/20 transition-colors flex items-center gap-2"
              >
                <Home className="w-5 h-5" />
                {VOCAB.controlPanel}
              </Link>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Find the main UI component (supports both 'component' and 'ui_component' artifact types)
  const isUIComponent = (type: string) => type === 'component' || type === 'ui_component';
  const mainComponent = projectData.artifacts.find(
    a => isUIComponent(a.artifactType) && (a.fileName.includes('Page') || a.fileName.includes('page') || a.fileName.includes('dashboard'))
  ) || projectData.artifacts.find(a => isUIComponent(a.artifactType));

  return (
    <div className="min-h-screen bg-brand-bg">
      <InternalHeader />
      
      {/* App Header Bar */}
      <div className="pt-20 border-b border-white/10 bg-brand-bg-elevated">
        <div className="max-w-7xl mx-auto px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <Link 
                href="/ghost-control/dark-factory" 
                className="text-gray-400 hover:text-white transition-colors"
              >
                <ArrowLeft className="w-5 h-5" />
              </Link>
              <div>
                <h1 className="text-xl font-bold text-white">{projectData.project.name}</h1>
                <p className="text-sm text-gray-400">
                  Generated by {VOCAB.factory} • {projectData.artifacts.length} artifacts
                </p>
              </div>
            </div>
            <button
              onClick={() => setShowFeedback(!showFeedback)}
              className="flex items-center gap-2 px-4 py-2 text-sm text-gray-300 hover:text-white bg-white/5 hover:bg-white/10 rounded-lg transition-colors"
            >
              <Bug className="w-4 h-4" />
              Report Issue
            </button>
          </div>
          
          {/* Feedback Panel */}
          {showFeedback && (
            <div className="mt-4 p-4 bg-white/5 rounded-lg border border-white/10">
              {submitted ? (
                <div className="flex items-center gap-2 text-green-400">
                  <CheckCircle className="w-5 h-5" />
                  Thank you! Your feedback has been recorded.
                </div>
              ) : (
                <div className="space-y-3">
                  <textarea
                    value={feedback}
                    onChange={(e) => setFeedback(e.target.value)}
                    placeholder="Describe the issue or suggestion..."
                    className="w-full px-4 py-3 bg-black/30 border border-white/10 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-brand-deep/50 resize-none"
                    rows={3}
                  />
                  <div className="flex justify-end gap-2">
                    <button
                      onClick={() => setShowFeedback(false)}
                      className="px-4 py-2 text-sm text-gray-400 hover:text-white"
                    >
                      Cancel
                    </button>
                    <button
                      onClick={handleFeedback}
                      disabled={submitting || !feedback.trim()}
                      className="px-4 py-2 text-sm bg-brand-deep text-white rounded-lg hover:bg-brand-deep disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {submitting ? 'Submitting...' : 'Submit Feedback'}
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* App Content */}
      <div className="max-w-7xl mx-auto px-6 py-8">
        {/* Show preview of generated code - TODO: Actually render the component */}
        <div className="glass-card p-6">
          <div className="flex items-center gap-3 mb-6">
            <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-brand-deep to-brand-secondary flex items-center justify-center">
              <Code className="w-5 h-5 text-white" />
            </div>
            <div>
              <h2 className="text-lg font-semibold text-white">Preview Mode</h2>
              <p className="text-sm text-gray-400">This app is running in preview mode from generated artifacts</p>
            </div>
          </div>
          
          {mainComponent ? (
            <div className="space-y-4">
              {/* Live Demo Banner */}
              <div className="p-4 bg-gradient-to-r from-brand-deep/20 to-brand-secondary/20 rounded-lg border border-brand-deep/30">
                <div className="flex items-center justify-between">
                  <div>
                    <h3 className="text-white font-medium mb-1">🚀 Want to see it in action?</h3>
                    <p className="text-sm text-gray-400">Try our working Task List demo to see what {VOCAB.factory} can build</p>
                  </div>
                  <Link
                    href="/apps/demo-tasks"
                    className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-brand-deep to-brand-secondary text-white rounded-lg hover:opacity-90 transition-opacity whitespace-nowrap"
                  >
                    <Code className="w-4 h-4" />
                    View Live Demo
                  </Link>
                </div>
              </div>

              <div className="flex items-center justify-between p-3 bg-black/20 rounded-lg border border-white/10">
                <div className="flex items-center gap-3">
                  <CheckCircle className="w-5 h-5 text-green-400" />
                  <span className="text-white font-medium">{mainComponent.fileName}</span>
                </div>
                <span className="text-xs px-2 py-1 bg-brand-deep/20 text-brand-light rounded">
                  {mainComponent.artifactType}
                </span>
              </div>
              
              {/* Code Preview */}
              <div className="relative">
                <pre className="p-4 bg-black/40 rounded-lg border border-white/10 overflow-x-auto max-h-96 text-sm">
                  <code className="text-gray-300">{mainComponent.code}</code>
                </pre>
              </div>
              
              <p className="text-sm text-gray-500 text-center">
                💡 The code above was generated by {VOCAB.factory} - click &quot;View Live Demo&quot; to interact with a working version
              </p>
            </div>
          ) : (
            <div className="text-center py-12">
              <AlertTriangle className="w-12 h-12 text-yellow-400 mx-auto mb-4" />
              <p className="text-gray-400">No UI component found in this project</p>
            </div>
          )}
        </div>
        
        {/* All Artifacts */}
        <div className="mt-8">
          <h3 className="text-lg font-semibold text-white mb-4">All Generated Artifacts</h3>
          <div className="grid gap-3">
            {projectData.artifacts.map((artifact) => (
              <div 
                key={artifact.id}
                className="p-4 bg-white/5 rounded-lg border border-white/10 hover:border-white/20 transition-colors"
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <Code className="w-4 h-4 text-gray-400" />
                    <span className="text-white">{artifact.fileName}</span>
                  </div>
                  <span className="text-xs px-2 py-1 bg-white/10 text-gray-300 rounded">
                    {artifact.artifactType}
                  </span>
                </div>
                <p className="text-xs text-gray-500 mt-1">{artifact.filePath}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
