// 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 
  } = 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({
          tech_stack_recommendations: 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);
    }
  };

  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"> 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>
          <button
            onClick={generateArchitecture}
            className="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition-colors"
          >
            Try Again
          </button>
        </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={() => window.history.back()}
            className="bg-gray-600 text-white px-6 py-2 rounded-lg hover:bg-gray-700 transition-colors"
          >
            Go Back
          </button>
        </div>
      </div>
    );
  }

  const { project_metadata, architecture_design, technology_specifications } = 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>
              <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 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 */}
        {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={architecture_design} />}
      </div>
    </div>
  );
}

// Overview Tab Component
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>
      </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
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">
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4">⚛️ React Architecture</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  
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">
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4">🟢 Node.js Architecture</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
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">
      <div className="bg-white rounded-xl shadow-sm border p-6">
        <h3 className="text-xl font-bold text-gray-900 mb-4">🐘 PostgreSQL Architecture</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
function DeploymentTab({ data }) {
  return (
    <div className="space-y-6">
      <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>
    </div>
  );
}
