import React, { useState, useEffect } from 'react';
import EnvironmentCard from '../components/EnvironmentCard';
import type { Environment, DeploymentStatus, Alert } from '../../types';

const Dashboard: React.FC = () => {
  const [environments, setEnvironments] = useState<Environment[]>([]);
  const [envStatuses, setEnvStatuses] = useState<Record<string, DeploymentStatus>>({});
  const [alerts, setAlerts] = useState<Alert[]>([]);
  const [stats, setStats] = useState({
    totalEnvironments: 0,
    enabledCount: 0,
    totalProviders: 0,
  });

  const environmentsByProvider = React.useMemo(() => {
    const grouped: Record<string, Environment[]> = {};
    environments.forEach(env => {
      const provider = env.provider || 'unknown';
      if (!grouped[provider]) {
        grouped[provider] = [];
      }
      grouped[provider].push(env);
    });
    return grouped;
  }, [environments]);

  const enabledPercentage = React.useMemo(() => {
    if (stats.totalEnvironments === 0) return 0;
    return Math.round((stats.enabledCount / stats.totalEnvironments) * 100);
  }, [stats]);

  const getProviderIcon = (provider: string): string => {
    const icons: Record<string, string> = {
      azure: 'fab fa-microsoft',
      aws: 'fab fa-aws',
      gcp: 'fab fa-google',
      ibm: 'fab fa-ibm',
      oci: 'fas fa-cloud',
      onprem: 'fas fa-server',
    };
    return icons[provider] || 'fas fa-server';
  };

  const loadData = async () => {
    try {
      const response = await fetch('/api/environments');
      const envs = await response.json();
      setEnvironments(envs);
      
      setStats({
        totalEnvironments: envs.length,
        enabledCount: envs.filter((e: Environment) => e.enabled).length,
        totalProviders: Object.keys(environmentsByProvider).length,
      });
      
      // Load statuses
      const statuses: Record<string, DeploymentStatus> = {};
      for (const env of envs) {
        if (env.enabled) {
          const statusResponse = await fetch(`/api/environments/${env.name}/status`);
          statuses[env.name] = await statusResponse.json();
        }
      }
      setEnvStatuses(statuses);
      
      // Load alerts
      const alertsResponse = await fetch('/api/alerts?unacknowledged_only=true');
      setAlerts(await alertsResponse.json());
    } catch (error) {
      console.error('Error loading data:', error);
    }
  };

  const handleDeploy = async (envName: string) => {
    try {
      const response = await fetch(`/api/environments/${envName}/deploy`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          strategy: 'blue-green',
          version: 'latest',
        }),
      });
      
      const data = await response.json();
      if (response.ok) {
        alert(`✅ Deployment queued: ${data.deployment_id}`);
        await loadData();
      } else {
        alert(`❌ Error: ${data.error}`);
      }
    } catch (error) {
      console.error('Deployment error:', error);
      alert(`❌ Error: ${error}`);
    }
  };

  useEffect(() => {
    loadData();
    const interval = setInterval(loadData, 30000);
    return () => clearInterval(interval);
  }, []);

  return (
    <div className="dashboard">
      {/* Statistics Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div className="stat-card">
          <h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-2">
            <i className="fas fa-server mr-2"></i>Total Environments
          </h3>
          <div className="text-3xl font-bold text-gray-900">{stats.totalEnvironments}</div>
          <div className="text-sm text-green-600 mt-2">+{stats.enabledCount} enabled</div>
        </div>
        
        <div className="stat-card">
          <h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-2">
            <i className="fas fa-check-circle mr-2"></i>Enabled
          </h3>
          <div className="text-3xl font-bold text-gray-900">{stats.enabledCount}</div>
          <div className="text-sm text-gray-600 mt-2">{enabledPercentage}% of total</div>
        </div>
        
        <div className="stat-card">
          <h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-2">
            <i className="fas fa-cloud mr-2"></i>Providers
          </h3>
          <div className="text-3xl font-bold text-gray-900">{stats.totalProviders}</div>
          <div className="text-sm text-gray-600 mt-2">Multi-cloud</div>
        </div>
        
        <div className="stat-card">
          <h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-2">
            <i className="fas fa-exclamation-triangle mr-2"></i>Active Alerts
          </h3>
          <div className="text-3xl font-bold text-gray-900">{alerts.length}</div>
          <div className={`text-sm mt-2 ${alerts.length > 0 ? 'text-red-600' : 'text-green-600'}`}>
            {alerts.length > 0 ? `${alerts.length} unacknowledged` : 'All clear'}
          </div>
        </div>
      </div>

      {/* Environments by Provider */}
      {Object.entries(environmentsByProvider).map(([provider, envs]) => (
        <div key={provider} className="mb-8">
          <div className="bg-white rounded-t-xl border-b-2 border-primary-500 px-6 py-4 flex justify-between items-center">
            <h2 className="text-2xl font-bold text-primary-600 flex items-center gap-2">
              <i className={getProviderIcon(provider)}></i>
              {provider.toUpperCase()} Environments
            </h2>
            <span className="text-gray-500">{envs.length} environment(s)</span>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 p-6 bg-white rounded-b-xl shadow-sm">
            {envs.map(env => (
              <EnvironmentCard
                key={env.name}
                environment={env}
                status={envStatuses[env.name]}
                onDeploy={handleDeploy}
              />
            ))}
          </div>
        </div>
      ))}
    </div>
  );
};

export default Dashboard;

