// ARCHITECTURE DESIGNER PAGE - Displays AI-generated architecture specifications
// Shows React + Node.js + PostgreSQL architecture from Architecture Designer service

import React, { useState, useEffect } from 'react';
import useProjectStore from '../../store/projectStore';

export default function ArchitectureDesigner() {
  const { 
    techStackRecommendations, 
    finalProjectData,
    setArchitectureDesign,
    architectureDesign,
    setCurrentStep
  } = useProjectStore();
  
  const [isGenerating, setIsGenerating] = useState(false);
  const [error, setError] = useState(null);
  const [activeTab, setActiveTab] = useState('overview');

  // Generate architecture on component mount if we have tech stack data
  useEffect(() => {
    if (techStackRecommendations && !architectureDesign) {
      generateArchitecture();
    }
  }, [techStackRecommendations]);

  const generateArchitecture = async () => {
    try {
      setIsGenerating(true);
      setError(null);

      console.log('🏗️ Generating architecture with data:', techStackRecommendations);

      const response = await fetch('http://localhost:8003/api/v1/design-architecture', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        
          body: JSON.stringify(techStackRecommendations)
        
      });

      if (!response.ok) {
        throw new Error(`Architecture generation failed: ${response.status}`);
      }

      const architectureResult = await response.json();
      console.log('✅ Architecture generated:', architectureResult);

      setArchitectureDesign(architectureResult);

    } catch (err) {
      console.error('❌ Architecture generation error:', err);
      setError(err.message);
    } finally {
      setIsGenerating(false);
    }
  };

  const handleBack = () => {
    setCurrentStep('summary');
  };

  if (isGenerating) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center">
        <div className="bg-white rounded-xl shadow-xl p-8 max-w-md w-full text-center">
          <div className="animate-spin rounded-full h-16 w-16 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <h2 className="text-xl font-bold text-gray-800 mb-2">🤖 AI Designing Your Architecture</h2>
          <p className="text-gray-600">Claude AI is analyzing your requirements and generating production-ready architecture specifications...</p>
          <div className="mt-4 bg-blue-50 rounded-lg p-3">
            <p className="text-sm text-blue-700">
              ⚡ Creating React components<br/>
              ⚡ Designing Node.js APIs<br/>
              ⚡ Generating PostgreSQL schema
            </p>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-red-50 to-pink-100 flex items-center justify-center">
        <div className="bg-white rounded-xl shadow-xl p-8 max-w-md w-full text-center">
          <div className="text-red-500 text-4xl mb-4">❌</div>
          <h2 className="text-xl font-bold text-gray-800 mb-2">Architecture Generation Failed</h2>
          <p className="text-gray-600 mb-4">{error}</p>
          <div className="space-x-3">
            <button
              onClick={generateArchitecture}
              className="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition-colors"
            >
              Try Again
            </button>
            <button
              onClick={handleBack}
              className="bg-gray-600 text-white px-6 py-2 rounded-lg hover:bg-gray-700 transition-colors"
            >
              ← Back
            </button>
          </div>
        </div>
      </div>
    );
  }

  if (!architectureDesign) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center">
        <div className="bg-white rounded-xl shadow-xl p-8 max-w-md w-full text-center">
          <h2 className="text-xl font-bold text-gray-800 mb-4">No Architecture Data</h2>
          <p className="text-gray-600 mb-4">Please complete the tech stack selection first.</p>
          <button
            onClick={handleBack}
            className="bg-gray-600 text-white px-6 py-2 rounded-lg hover:bg-gray-700 transition-colors"
          >
            ← Back to Tech Stack
          </button>
        </div>
      </div>
    );
  }

  // FIXED: Extract data from actual architecture-designer response
  const { project_metadata, architecture_design, technology_specifications, code_generation_ready } = architectureDesign;

  return (
    <div className="min-h-screen bg-gradient-to-br from-indigo-50 via-white to-cyan-50">
      {/* Header */}
      <div className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 py-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <button
                onClick={handleBack}
                className="bg-gray-100 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-200 transition-colors flex items-center space-x-2"
              >
                <span>←</span>
                <span>Back</span>
              </button>
              <div>
                <h1 className="text-3xl font-bold text-gray-900">
                  🏗️ Architecture Design
                </h1>
                <p className="text-gray-600 mt-1">
                  AI-generated production-ready architecture for <span className="font-semibold text-indigo-600">{project_metadata?.project_name}</span>
                </p>
              </div>
            </div>
            <div className="flex items-center space-x-4">
              <div className="bg-green-100 text-green-800 px-3 py-1 rounded-full text-sm font-medium">
                ✅ Architecture Ready
              </div>
              <button
                onClick={generateArchitecture}
                className="bg-indigo-600 text-white px-6 py-2 rounded-lg hover:bg-indigo-700 transition-colors flex items-center space-x-2"
              >
                <span>🔄</span>
                <span>Regenerate</span>
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="max-w-7xl mx-auto px-4 py-6">
        <div className="border-b border-gray-200 mb-6">
          <nav className="-mb-px flex space-x-8">
            {[
              { id: 'overview', name: '📋 Overview', icon: '🏗️' },
              { id: 'frontend', name: '🎨 Frontend (React)', icon: '⚛️' },
              { id: 'backend', name: '⚙️ Backend (Node.js)', icon: '🟢' },
              { id: 'database', name: '🗄️ Database (PostgreSQL)', icon: '🐘' },
              { id: 'deployment', name: '🚀 Deployment', icon: '☁️' }
            ].map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`py-2 px-1 border-b-2 font-medium text-sm transition-colors ${
                  activeTab === tab.id
                    ? 'border-indigo-500 text-indigo-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
              >
                <span className="flex items-center space-x-2">
                  <span>{tab.icon}</span>
                  <span>{tab.name}</span>
                </span>
              </button>
            ))}
          </nav>
        </div>

        {/* Tab Content - FIXED to use actual data */}
        {activeTab === 'overview' && <OverviewTab data={architectureDesign} />}
        {activeTab === 'frontend' && <FrontendTab data={architecture_design?.frontend_architecture} />}
        {activeTab === 'backend' && <BackendTab data={architecture_design?.backend_architecture} />}
        {activeTab === 'database' && <DatabaseTab data={architecture_design?.database_architecture} />}
        {activeTab === 'deployment' && <DeploymentTab data={architectureDesign} />}
      </div>
    </div>
  );
}

// Overview Tab Component - FIXED to display actual data
function OverviewTab({ data }) {
  const { project_metadata, technology_specifications, code_generation_ready } = data;

  return (
    <div className="space-y-6">
      {/* Project Overview */}
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4 flex items-center">
          <span className="text-2xl mr-2">📊</span>
          Project Overview
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="bg-blue-50 rounded-lg p-4">
            <h4 className="font-semibold text-blue-900">Project Name</h4>
            <p className="text-blue-700">{project_metadata?.project_name}</p>
          </div>
          <div className="bg-green-50 rounded-lg p-4">
            <h4 className="font-semibold text-green-900">Complexity</h4>
            <p className="text-green-700 capitalize">{project_metadata?.complexity}</p>
          </div>
          <div className="bg-purple-50 rounded-lg p-4">
            <h4 className="font-semibold text-purple-900">Generated</h4>
            <p className="text-purple-700">
              {new Date(project_metadata?.architecture_generated_at).toLocaleDateString()}
            </p>
          </div>
        </div>

        {/* Features Implemented */}
        {project_metadata?.features_implemented && project_metadata.features_implemented.length > 0 && (
          <div className="mt-6">
            <h4 className="font-semibold text-gray-800 mb-3">Features Implemented</h4>
            <div className="flex flex-wrap gap-2">
              {project_metadata.features_implemented.map((feature, index) => (
                <span key={index} className="bg-indigo-100 text-indigo-800 px-3 py-1 rounded-full text-sm">
                  {feature}
                </span>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Technology Stack */}
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4 flex items-center">
          <span className="text-2xl mr-2">🛠️</span>
          Technology Stack
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="bg-gradient-to-r from-blue-500 to-cyan-500 rounded-lg p-4 text-white">
            <h4 className="font-semibold">⚛️ Frontend</h4>
            <p className="text-lg">{technology_specifications?.frontend_framework}</p>
            <p className="text-sm opacity-90">React 18+ with modern hooks</p>
          </div>
          <div className="bg-gradient-to-r from-green-500 to-emerald-500 rounded-lg p-4 text-white">
            <h4 className="font-semibold">🟢 Backend</h4>
            <p className="text-lg">{technology_specifications?.backend_language}</p>
            <p className="text-sm opacity-90">Express.js with TypeScript</p>
          </div>
          <div className="bg-gradient-to-r from-indigo-500 to-blue-500 rounded-lg p-4 text-white">
            <h4 className="font-semibold">🐘 Database</h4>
            <p className="text-lg">{technology_specifications?.database_system}</p>
            <p className="text-sm opacity-90">PostgreSQL 14+ with advanced features</p>
          </div>
        </div>
      </div>

      {/* Code Generation Status */}
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4 flex items-center">
          <span className="text-2xl mr-2">🚀</span>
          Code Generation Ready
        </h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {Object.entries(code_generation_ready || {}).map(([key, value]) => (
            <div key={key} className="flex items-center space-x-2">
              <span className={`text-2xl ${value ? '✅' : '❌'}`}></span>
              <span className="text-sm font-medium text-gray-700 capitalize">
                {key.replace(/_/g, ' ')}
              </span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// Frontend Tab Component - FIXED to display actual frontend architecture
function FrontendTab({ data }) {
  if (!data) {
    return <div className="text-center py-8 text-gray-500">Frontend architecture data not available</div>;
  }

  return (
    <div className="space-y-6">
      {/* Folder Structure */}
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4">📁 Folder Structure</h3>
        <div className="bg-gray-50 rounded-lg p-4">
          {Object.entries(data.folder_structure || {}).map(([folder, description]) => (
            <div key={folder} className="flex justify-between items-start mb-2 last:mb-0">
              <code className="text-blue-600 font-mono text-sm">{folder}/</code>
              <span className="text-gray-600 text-sm ml-4">{description}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Components */}
      {data.components_for_feature && (
        <div className="bg-white rounded-xl shadow-sm border p-6">
          <h3 className="text-xl font-bold text-gray-900 mb-4">⚛️ React Components</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {Object.entries(data.components_for_feature).map(([component, description]) => (
              <div key={component} className="bg-blue-50 rounded-lg p-4">
                <h4 className="font-semibold text-blue-900">{component}</h4>
                <p className="text-blue-700 text-sm">{description}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Technical Specifications */}
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4">🔧 Technical Specifications</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="bg-purple-50 rounded-lg p-4">
            <h4 className="font-semibold text-purple-900">UI Library</h4>
            <p className="text-purple-700">{data.ui_library}</p>
          </div>
          <div className="bg-green-50 rounded-lg p-4">
            <h4 className="font-semibold text-green-900">State Management</h4>
            <p className="text-green-700">{data.state_management}</p>
          </div>
          <div className="bg-orange-50 rounded-lg p-4">
            <h4 className="font-semibold text-orange-900">Routing</h4>
            <p className="text-orange-700">{data.routing}</p>
          </div>
        </div>
      </div>

      {/* Raw Data for Development */}
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4">📄 Raw Architecture Data</h3>
        <pre className="bg-gray-50 rounded-lg p-4 overflow-x-auto text-sm">
          {JSON.stringify(data, null, 2)}
        </pre>
      </div>
    </div>
  );
}

// Backend Tab Component - FIXED to display actual backend architecture
function BackendTab({ data }) {
  if (!data) {
    return <div className="text-center py-8 text-gray-500">Backend architecture data not available</div>;
  }

  return (
    <div className="space-y-6">
      {/* Folder Structure */}
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4">📁 Folder Structure</h3>
        <div className="bg-gray-50 rounded-lg p-4">
          {Object.entries(data.folder_structure || {}).map(([folder, description]) => (
            <div key={folder} className="flex justify-between items-start mb-2 last:mb-0">
              <code className="text-green-600 font-mono text-sm">{folder}/</code>
              <span className="text-gray-600 text-sm ml-4">{description}</span>
            </div>
          ))}
        </div>
      </div>

      {/* API Endpoints */}
      {data.api_endpoints && (
        <div className="bg-white rounded-xl shadow-sm border p-6">
          <h3 className="text-xl font-bold text-gray-900 mb-4">🔌 API Endpoints</h3>
          <div className="space-y-3">
            {Object.entries(data.api_endpoints).map(([category, endpoints]) => (
              <div key={category} className="bg-green-50 rounded-lg p-4">
                <h4 className="font-semibold text-green-900 capitalize">{category}</h4>
                <p className="text-green-700 text-sm">{endpoints}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Database Integration */}
      {data.database_integration && (
        <div className="bg-white rounded-xl shadow-sm border p-6">
          <h3 className="text-xl font-bold text-gray-900 mb-4">🗄️ Database Integration</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="bg-indigo-50 rounded-lg p-4">
              <h4 className="font-semibold text-indigo-900">Primary Database</h4>
              <p className="text-indigo-700">{data.database_integration.primary_database}</p>
            </div>
            <div className="bg-purple-50 rounded-lg p-4">
              <h4 className="font-semibold text-purple-900">ORM Choice</h4>
              <p className="text-purple-700">{data.database_integration.orm_choice}</p>
            </div>
          </div>
        </div>
      )}

      {/* Authentication */}
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4">🔐 Authentication</h3>
        <div className="bg-yellow-50 rounded-lg p-4">
          <p className="text-yellow-700">{data.authentication}</p>
        </div>
      </div>

      {/* Raw Data for Development */}
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4">📄 Raw Architecture Data</h3>
        <pre className="bg-gray-50 rounded-lg p-4 overflow-x-auto text-sm">
          {JSON.stringify(data, null, 2)}
        </pre>
      </div>
    </div>
  );
}

// Database Tab Component - FIXED to display actual database architecture
function DatabaseTab({ data }) {
  if (!data) {
    return <div className="text-center py-8 text-gray-500">Database architecture data not available</div>;
  }

  return (
    <div className="space-y-6">
      {/* Database Schema */}
      {data.database_schema && (
        <div className="bg-white rounded-xl shadow-sm border p-6">
          <h3 className="text-xl font-bold text-gray-900 mb-4">🗄️ Database Schema</h3>
          <div className="bg-gray-50 rounded-lg p-4">
            <p className="text-gray-600 text-sm mb-3">{data.database_schema.note}</p>
            <div className="space-y-2">
              {Object.entries(data.database_schema.tables || {}).map(([table, description]) => (
                <div key={table} className="flex justify-between items-start">
                  <code className="text-purple-600 font-mono text-sm">{table}</code>
                  <span className="text-gray-600 text-sm ml-4">{description}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* Security Implementation */}
      {data.security_implementation && (
        <div className="bg-white rounded-xl shadow-sm border p-6">
          <h3 className="text-xl font-bold text-gray-900 mb-4">🔒 Security Implementation</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="bg-red-50 rounded-lg p-4">
              <h4 className="font-semibold text-red-900">Authentication</h4>
              <p className="text-red-700">{data.security_implementation.authentication}</p>
            </div>
            <div className="bg-red-50 rounded-lg p-4">
              <h4 className="font-semibold text-red-900">SSL</h4>
              <p className="text-red-700">{data.security_implementation.ssl}</p>
            </div>
          </div>
        </div>
      )}

      {/* Backup Strategy */}
      {data.backup_strategy && (
        <div className="bg-white rounded-xl shadow-sm border p-6">
          <h3 className="text-xl font-bold text-gray-900 mb-4">💾 Backup Strategy</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="bg-blue-50 rounded-lg p-4">
              <h4 className="font-semibold text-blue-900">Method</h4>
              <p className="text-blue-700">{data.backup_strategy.method}</p>
            </div>
            <div className="bg-blue-50 rounded-lg p-4">
              <h4 className="font-semibold text-blue-900">Retention</h4>
              <p className="text-blue-700">{data.backup_strategy.retention}</p>
            </div>
          </div>
        </div>
      )}

      {/* Raw Data for Development */}
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4">📄 Raw Architecture Data</h3>
        <pre className="bg-gray-50 rounded-lg p-4 overflow-x-auto text-sm">
          {JSON.stringify(data, null, 2)}
        </pre>
      </div>
    </div>
  );
}

// Deployment Tab Component - Shows deployment info
function DeploymentTab({ data }) {
  const { project_metadata, code_generation_ready } = data;

  return (
    <div className="space-y-6">
      {/* Deployment Status */}
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4">🚀 Deployment Status</h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {Object.entries(code_generation_ready || {}).map(([key, value]) => (
            <div key={key} className="flex items-center space-x-2">
              <span className={`text-2xl ${value ? '✅' : '❌'}`}></span>
              <span className="text-sm font-medium text-gray-700 capitalize">
                {key.replace(/_/g, ' ')}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* Deployment Configuration */}
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4">☁️ Deployment Configuration</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="bg-blue-50 rounded-lg p-4">
            <h4 className="font-semibold text-blue-900 mb-2">Frontend Deployment</h4>
            <ul className="text-blue-700 text-sm space-y-1">
              <li>• Vercel/Netlify hosting</li>
              <li>• React build optimization</li>
              <li>• CDN distribution</li>
            </ul>
          </div>
          <div className="bg-green-50 rounded-lg p-4">
            <h4 className="font-semibold text-green-900 mb-2">Backend Deployment</h4>
            <ul className="text-green-700 text-sm space-y-1">
              <li>• Docker containerization</li>
              <li>• AWS/GCP hosting</li>
              <li>• Auto-scaling setup</li>
            </ul>
          </div>
        </div>
      </div>

      {/* Project Information */}
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4">📊 Project Information</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="bg-gray-50 rounded-lg p-4">
            <h4 className="font-semibold text-gray-900">Project ID</h4>
            <p className="text-gray-700 text-sm font-mono">{project_metadata?.project_id}</p>
          </div>
          <div className="bg-gray-50 rounded-lg p-4">
            <h4 className="font-semibold text-gray-900">AI Powered</h4>
            <p className="text-gray-700">{project_metadata?.ai_powered ? 'Yes' : 'No'}</p>
          </div>
          <div className="bg-gray-50 rounded-lg p-4">
            <h4 className="font-semibold text-gray-900">Dynamic Design</h4>
            <p className="text-gray-700">{project_metadata?.dynamic_design ? 'Yes' : 'No'}</p>
          </div>
        </div>
      </div>
    </div>
  );
}