// Deployment Status Page
// Real-time deployment tracking

import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { apiClient } from '@/services/api/client';

interface DeploymentStatus {
  subscriptionId: string;
  status: string;
  deployedAt?: Date;
  containers: any[];
  network: any;
  health: string;
}

export const DeploymentStatus: React.FC = () => {
  const { subscriptionId } = useParams<{ subscriptionId?: string }>();
  const [deployment, setDeployment] = useState<DeploymentStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchDeployment = async () => {
      if (!subscriptionId) {
        setError('Subscription ID required');
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        const data = await apiClient.get<{ success: boolean; data: DeploymentStatus }>(
          `/api/v1/iru/portal/deployment/${subscriptionId}`
        );
        if (data.success) {
          setDeployment(data.data);
        }
      } catch (err: any) {
        setError(err.message || 'Failed to load deployment status');
      } finally {
        setLoading(false);
      }
    };

    fetchDeployment();
    const interval = setInterval(fetchDeployment, 10000); // Refresh every 10 seconds
    return () => clearInterval(interval);
  }, [subscriptionId]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading deployment status...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="text-red-600 text-xl mb-4">Error</div>
          <p className="text-gray-600">{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="container mx-auto px-4">
        <h1 className="text-3xl font-bold mb-8 text-gray-800">Deployment Status</h1>

        {deployment && (
          <div className="space-y-6">
            {/* Status Card */}
            <div className="bg-white rounded-lg shadow p-6">
              <h2 className="text-2xl font-semibold mb-4 text-gray-800">Deployment Status</h2>
              <div className="flex items-center gap-4">
                <span className={`text-4xl font-bold ${
                  deployment.status === 'deployed'
                    ? 'text-green-600'
                    : deployment.status === 'pending'
                    ? 'text-yellow-600'
                    : 'text-red-600'
                }`}>
                  {deployment.status === 'deployed' ? '✓' : deployment.status === 'pending' ? '⏳' : '✗'}
                </span>
                <div>
                  <div className="text-lg font-semibold text-gray-800 capitalize">
                    {deployment.status}
                  </div>
                  {deployment.deployedAt && (
                    <div className="text-sm text-gray-500">
                      Deployed: {new Date(deployment.deployedAt).toLocaleString()}
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* Containers */}
            <div className="bg-white rounded-lg shadow p-6">
              <h2 className="text-2xl font-semibold mb-4 text-gray-800">Containers</h2>
              {deployment.containers.length > 0 ? (
                <div className="space-y-2">
                  {deployment.containers.map((container: any, index: number) => (
                    <div key={index} className="flex items-center justify-between bg-gray-50 p-3 rounded">
                      <div>
                        <div className="font-medium text-gray-800">{container.name || `Container ${index + 1}`}</div>
                        <div className="text-sm text-gray-500">{container.status || 'Unknown'}</div>
                      </div>
                      <span className={`px-2 py-1 rounded text-sm font-semibold ${
                        container.status === 'running'
                          ? 'bg-green-100 text-green-800'
                          : 'bg-yellow-100 text-yellow-800'
                      }`}>
                        {container.status || 'Unknown'}
                      </span>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-gray-600">No containers deployed yet.</p>
              )}
            </div>

            {/* Network */}
            <div className="bg-white rounded-lg shadow p-6">
              <h2 className="text-2xl font-semibold mb-4 text-gray-800">Network Configuration</h2>
              {Object.keys(deployment.network).length > 0 ? (
                <pre className="bg-gray-50 p-4 rounded text-sm text-gray-700">
                  {JSON.stringify(deployment.network, null, 2)}
                </pre>
              ) : (
                <p className="text-gray-600">Network configuration not available.</p>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default DeploymentStatus;
