/**
 * System Monitoring Page
 */

import React, { useState } from 'react';
import {
  CacheStatsCard,
  DatabaseStatsGrid,
  ProxyStatsCard,
  QueueStatsTable,
  ServiceStatusGrid,
  SystemHealthCard
} from './components';
import {
  useCacheStats,
  useDatabaseStats,
  useProxyStats,
  useQueueStats,
  useServiceStatus,
  useSystemHealth,
  useSystemOverview
} from './hooks';

export function MonitoringPage() {
  const [refreshInterval, setRefreshInterval] = useState(5000); // 5 seconds default
  const [useOverview, setUseOverview] = useState(false); // Toggle between individual calls and overview
  
  // Individual API calls
  const { data: health, loading: healthLoading, error: healthError } = useSystemHealth(useOverview ? 0 : refreshInterval);
  const { data: cache, loading: cacheLoading, error: cacheError } = useCacheStats(useOverview ? 0 : refreshInterval);
  const { data: queues, loading: queuesLoading, error: queuesError } = useQueueStats(useOverview ? 0 : refreshInterval);
  const { data: databases, loading: dbLoading, error: dbError } = useDatabaseStats(useOverview ? 0 : refreshInterval);
  const { data: services, loading: servicesLoading, error: servicesError } = useServiceStatus(useOverview ? 0 : refreshInterval);
  const { data: proxies, loading: proxiesLoading, error: proxiesError } = useProxyStats(useOverview ? 0 : refreshInterval);
  
  // Combined overview call
  const { data: overview, loading: overviewLoading, error: overviewError } = useSystemOverview(useOverview ? refreshInterval : 0);

  const handleRefreshIntervalChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setRefreshInterval(Number(e.target.value));
  };

  const handleDataSourceToggle = () => {
    setUseOverview(!useOverview);
  };

  // Use overview data if enabled
  const displayHealth = useOverview && overview ? overview.health : health;
  const displayServices = useOverview && overview ? overview.services : services;
  const displayProxies = useOverview && overview ? overview.proxies : proxies;
  const displayCache = useOverview && overview ? overview.health.services.cache : cache;
  const displayQueues = useOverview && overview ? overview.health.services.queues : queues;
  const displayDatabases = useOverview && overview ? overview.health.services.databases : databases;

  const isLoading = useOverview 
    ? overviewLoading 
    : (healthLoading || cacheLoading || queuesLoading || dbLoading || servicesLoading || proxiesLoading);

  const errors = useOverview 
    ? (overviewError ? [overviewError] : [])
    : [healthError, cacheError, queuesError, dbError, servicesError, proxiesError].filter(Boolean);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-500 mx-auto"></div>
          <p className="mt-4 text-text-secondary">Loading monitoring data...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full space-y-4">
      <div className="flex items-center justify-between flex-shrink-0">
        <div>
          <h1 className="text-lg font-bold text-text-primary mb-2">System Monitoring</h1>
        </div>
          <div className="flex items-center space-x-4">
            <div className="flex items-center space-x-2">
              <label className="text-sm text-text-secondary">
                Data source:
              </label>
              <button
                onClick={handleDataSourceToggle}
                className={`px-3 py-1 rounded text-sm font-medium transition-colors ${
                  useOverview 
                    ? 'bg-primary-600 text-white' 
                    : 'bg-surface-tertiary text-text-primary'
                }`}
              >
                {useOverview ? 'Overview API' : 'Individual APIs'}
              </button>
            </div>
            <div className="flex items-center space-x-2">
              <label htmlFor="refresh-interval" className="text-sm text-text-secondary">
                Refresh interval:
              </label>
              <select
                id="refresh-interval"
                value={refreshInterval}
                onChange={handleRefreshIntervalChange}
                className="text-sm bg-surface-secondary border border-border text-text-primary rounded px-2 py-1"
              >
                <option value={0}>Manual</option>
                <option value={5000}>5 seconds</option>
                <option value={10000}>10 seconds</option>
                <option value={30000}>30 seconds</option>
                <option value={60000}>1 minute</option>
              </select>
            </div>
          </div>
      </div>

      {errors.length > 0 && (
        <div className="p-3 bg-danger/10 border border-danger rounded-lg flex-shrink-0">
          <h3 className="font-semibold text-danger mb-2">Errors occurred while fetching data:</h3>
          <ul className="list-disc list-inside text-sm text-danger space-y-1">
            {errors.map((error, index) => (
              <li key={index}>{error}</li>
            ))}
          </ul>
        </div>
      )}

      {useOverview && overview && (
        <div className="p-3 bg-primary-500/10 border border-primary-500 rounded-lg flex-shrink-0">
          <h3 className="font-semibold text-primary-400 mb-2">System Environment</h3>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
            <div>
              <span className="text-primary-400">Node:</span> <span className="text-text-primary">{overview.environment.nodeVersion}</span>
            </div>
            <div>
              <span className="text-primary-400">Platform:</span> <span className="text-text-primary">{overview.environment.platform}</span>
            </div>
            <div>
              <span className="text-primary-400">Architecture:</span> <span className="text-text-primary">{overview.environment.architecture}</span>
            </div>
            <div>
              <span className="text-primary-400">Hostname:</span> <span className="text-text-primary">{overview.environment.hostname}</span>
            </div>
          </div>
        </div>
      )}

      <div className="flex-1 min-h-0 space-y-4">
        {/* Service Status */}
        {displayServices && displayServices.length > 0 && (
          <div>
            <h2 className="text-lg font-semibold mb-3 text-text-primary">Microservices Status</h2>
            <ServiceStatusGrid services={displayServices} />
          </div>
        )}

        {/* System Health and Cache */}
        {displayHealth && (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
            <div className="lg:col-span-1">
              <SystemHealthCard health={displayHealth} />
            </div>
            <div className="lg:col-span-1">
              {displayCache && <CacheStatsCard stats={displayCache} />}
            </div>
            <div className="lg:col-span-1">
              {displayProxies && <ProxyStatsCard stats={displayProxies} />}
            </div>
          </div>
        )}

        {/* Database Stats */}
        {displayDatabases && displayDatabases.length > 0 && (
          <div>
            <h2 className="text-lg font-semibold mb-3 text-text-primary">Database Connections</h2>
            <DatabaseStatsGrid databases={displayDatabases} />
          </div>
        )}

        {/* Queue Stats */}
        {displayQueues && displayQueues.length > 0 && (
          <div>
            <h2 className="text-lg font-semibold mb-3 text-text-primary">Queue Status</h2>
            <QueueStatsTable queues={displayQueues} />
          </div>
        )}
      </div>
    </div>
  );
}