'use client';

import React, { useState, useEffect } from 'react';
import { 
  RewardDashboard, 
  WalletBalance, 
  PayrollManagement,
  PayrollErrorBoundary,
  useErrorHandler
} from '../../features/payroll-reward-system/components';
import { PayrollRewardSystemModule } from '../../features/payroll-reward-system';
import { setupGlobalErrorHandling } from '../../core/errors';
import { container as globalContainer } from '../../core/di/DIContainer';
import DashboardLayout from '@/layouts/DashboardLayout';

export default function PayrollDemoPage() {
  const [moduleLoaded, setModuleLoaded] = useState(false);
  const [activeTab, setActiveTab] = useState<'rewards' | 'wallet' | 'payroll'>('rewards');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { handleError } = useErrorHandler();

  useEffect(() => {
    // Setup global error handling
    setupGlobalErrorHandling();
    initializeModule();
  }, []);

  const initializeModule = async () => {
    try {
      setLoading(true);
      setError(null);

      // Create module instance
      const moduleInstance = new PayrollRewardSystemModule();

      // Activate the module first (this initializes the services)
      await moduleInstance.activate();
      
      // Get services after activation
      const services = moduleInstance.getServices();
      
      // Register services with container using lazy initialization to avoid circular dependency
      for (const serviceConfig of services) {
        try {
          console.log(`Registering service: ${serviceConfig.token}`);
          
          // Check if service is already registered to prevent duplicates
          if (globalContainer.has(serviceConfig.token)) {
            console.log(`Service ${serviceConfig.token} already registered, skipping`);
            continue;
          }
          
          // Register as singleton with lazy factory to avoid circular dependency
          globalContainer.singleton(serviceConfig.token, () => {
            const serviceInstance = serviceConfig.factory();
            console.log(`Created service instance: ${serviceConfig.token}`);
            return serviceInstance;
          });
          
          console.log(`✅ Registered service: ${serviceConfig.token}`);
        } catch (serviceError) {
          console.error(`❌ Failed to register service ${serviceConfig.token}:`, serviceError);
          throw new Error(`Failed to register ${serviceConfig.token}: ${serviceError instanceof Error ? serviceError.message : 'Unknown error'}`);
        }
      }

      setModuleLoaded(true);
      console.log('🎉 Payroll Reward System module loaded successfully');
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to initialize module';
      setError(errorMessage);
      console.error('❌ Failed to initialize module:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleHealthCheck = async () => {
    try {
      const moduleInstance = new PayrollRewardSystemModule();
      const isHealthy = await moduleInstance.isHealthy();
      alert(`Module Health Status: ${isHealthy ? 'Healthy ✅' : 'Unhealthy ❌'}`);
    } catch (err) {
      alert(`Health check failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
    }
  };

  if (loading) {
    return (
      <DashboardLayout>
        <div className="min-h-[calc(100vh-4rem)] bg-gray-50 flex items-center justify-center">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
            <p className="text-gray-600">Loading Payroll Reward System...</p>
          </div>
        </div>
      </DashboardLayout>
    );
  }

  if (error) {
    return (
      <DashboardLayout>
        <div className="min-h-[calc(100vh-4rem)] bg-gray-50 flex items-center justify-center">
          <div className="text-center max-w-md">
            <div className="text-6xl mb-4">❌</div>
            <h1 className="text-2xl font-bold text-gray-900 mb-2">Module Load Error</h1>
            <p className="text-gray-600 mb-4">{error}</p>
            <button
              onClick={initializeModule}
              className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
            >
              Retry
            </button>
          </div>
        </div>
      </DashboardLayout>
    );
  }

  return (
    <DashboardLayout>
      <PayrollErrorBoundary>
      <div className="min-h-[calc(100vh-4rem)] bg-gray-50">
        {/* Header */}
        <div className="bg-white shadow-sm border-b">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex justify-between items-center py-4">
              <div>
                <h1 className="text-2xl font-bold text-gray-900">
                  🎯 Payroll Reward System
                </h1>
                <p className="text-gray-600">
                  Modular Payroll Reward System
                </p>
              </div>
              
              <div className="flex items-center space-x-4">
                <div className="flex items-center space-x-2">
                  <div className="w-3 h-3 bg-green-500 rounded-full"></div>
                  <span className="text-sm text-gray-600">Module Active</span>
                </div>
                
                <button
                  onClick={handleHealthCheck}
                  className="bg-gray-100 text-gray-700 px-3 py-1 rounded text-sm hover:bg-gray-200"
                >
                  🏥 Health Check
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Navigation Tabs */}
        <div className="bg-white border-b">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <nav className="flex space-x-8">
              {[
                { id: 'rewards', label: 'Reward Dashboard', icon: '🎁' },
                { id: 'wallet', label: 'Wallet Balance', icon: '💰' },
                { id: 'payroll', label: 'Payroll Management', icon: '📊' }
              ].map(tab => (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id as any)}
                  className={`py-4 px-1 border-b-2 font-medium text-sm ${
                    activeTab === tab.id
                      ? 'border-blue-500 text-blue-600'
                      : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                  }`}
                >
                  <span className="mr-2">{tab.icon}</span>
                  {tab.label}
                </button>
              ))}
            </nav>
          </div>
        </div>

      {/* Content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

        {/* Component Content */}
        {moduleLoaded && (
          <div>
            {activeTab === 'rewards' && (
              <RewardDashboard 
                userId="demo-user-123"
                className="mb-6"
              />
            )}
            
            {activeTab === 'wallet' && (
              <WalletBalance 
                userId="demo-user-123"
                className="mb-6"
                showTransactions={true}
              />
            )}
            
            {activeTab === 'payroll' && (
              <PayrollManagement 
                className="mb-6"
                userRole="admin"
              />
            )}
          </div>
        )}
      </div>
    </div>
    </PayrollErrorBoundary>
    </DashboardLayout>
  );
}