import { useState, useEffect, useCallback } from 'react';
import { 
  Activity, 
  Zap, 
  Database, 
  Server, 
  Workflow,
  Globe,
  CheckCircle,
  AlertTriangle,
  XCircle,
  RefreshCw,
  TrendingUp,
  Clock,
  Cpu,
  HardDrive,
  MemoryStick
} from 'lucide-react';
import PageMeta from '../../components/common/PageMeta';
import DebugSiteSelector from '../../components/common/DebugSiteSelector';
import { fetchAPI } from '../../services/api';
import { useSiteStore } from '../../store/siteStore';

// Types
interface SystemMetrics {
  cpu: { usage_percent: number; cores: number; status: string };
  memory: { total_gb: number; used_gb: number; usage_percent: number; status: string };
  disk: { total_gb: number; used_gb: number; usage_percent: number; status: string };
}

interface ServiceHealth {
  database: { status: string; connected: boolean };
  redis: { status: string; connected: boolean };
  celery: { status: string; worker_count: number };
}

interface ApiGroupHealth {
  name: string;
  total: number;
  healthy: number;
  warning: number;
  error: number;
  percentage: number;
  status: 'healthy' | 'warning' | 'error';
}

interface WorkflowHealth {
  name: string;
  steps: { name: string; status: 'healthy' | 'warning' | 'error'; message?: string }[];
  overall: 'healthy' | 'warning' | 'error';
}

interface IntegrationHealth {
  platform: string;
  connected: boolean;
  last_sync: string | null;
  sync_enabled: boolean;
  plugin_active: boolean;
  status: 'healthy' | 'warning' | 'error';
}

export default function MasterStatus() {
  const { activeSite } = useSiteStore();
  const [loading, setLoading] = useState(true);
  const [lastUpdate, setLastUpdate] = useState<Date>(new Date());
  
  // System metrics
  const [systemMetrics, setSystemMetrics] = useState<SystemMetrics | null>(null);
  const [serviceHealth, setServiceHealth] = useState<ServiceHealth | null>(null);
  
  // API health
  const [apiHealth, setApiHealth] = useState<ApiGroupHealth[]>([]);
  
  // Workflow health (keywords → clusters → ideas → tasks → content → publish)
  const [workflowHealth, setWorkflowHealth] = useState<WorkflowHealth[]>([]);
  
  // Integration health
  const [integrationHealth, setIntegrationHealth] = useState<IntegrationHealth | null>(null);

  // Fetch system metrics
  const fetchSystemMetrics = useCallback(async () => {
    try {
      const data = await fetchAPI('/v1/system/status/');
      setSystemMetrics(data.system);
      setServiceHealth({
        database: data.database,
        redis: data.redis,
        celery: data.celery,
      });
    } catch (error) {
      console.error('Failed to fetch system metrics:', error);
    }
  }, []);

  // Fetch API health (aggregated from API monitor)
  const fetchApiHealth = useCallback(async () => {
    const groups = [
      { name: 'Auth & User', endpoints: ['/v1/auth/me/', '/v1/auth/sites/', '/v1/auth/accounts/'] },
      { name: 'Planner', endpoints: ['/v1/planner/keywords/', '/v1/planner/clusters/', '/v1/planner/ideas/'] },
      { name: 'Writer', endpoints: ['/v1/writer/tasks/', '/v1/writer/content/', '/v1/writer/images/'] },
      { name: 'Integration', endpoints: ['/v1/integration/integrations/'] },
    ];

    const healthChecks: ApiGroupHealth[] = [];

    for (const group of groups) {
      let healthy = 0;
      let warning = 0;
      let error = 0;

      for (const endpoint of group.endpoints) {
        try {
          const startTime = Date.now();
          await fetchAPI(endpoint + (activeSite ? `?site=${activeSite.id}` : ''));
          const responseTime = Date.now() - startTime;
          
          if (responseTime < 1000) healthy++;
          else if (responseTime < 3000) warning++;
          else error++;
        } catch (e) {
          error++;
        }
      }

      const total = group.endpoints.length;
      const percentage = Math.round((healthy / total) * 100);
      
      healthChecks.push({
        name: group.name,
        total,
        healthy,
        warning,
        error,
        percentage,
        status: error > 0 ? 'error' : warning > 0 ? 'warning' : 'healthy',
      });
    }

    setApiHealth(healthChecks);
  }, [activeSite]);

  // Check workflow health (end-to-end pipeline)
  const checkWorkflowHealth = useCallback(async () => {
    if (!activeSite) {
      setWorkflowHealth([]);
      return;
    }

    const workflows: WorkflowHealth[] = [];

    // Content Generation Workflow
    try {
      const steps = [];
      
      // Step 1: Keywords exist
      const keywords = await fetchAPI(`/v1/planner/keywords/?site=${activeSite.id}`);
      steps.push({
        name: 'Keywords Imported',
        status: keywords.count > 0 ? 'healthy' : 'warning' as const,
        message: `${keywords.count} keywords`,
      });

      // Step 2: Clusters exist
      const clusters = await fetchAPI(`/v1/planner/clusters/?site=${activeSite.id}`);
      steps.push({
        name: 'Content Clusters',
        status: clusters.count > 0 ? 'healthy' : 'warning' as const,
        message: `${clusters.count} clusters`,
      });

      // Step 3: Ideas generated
      const ideas = await fetchAPI(`/v1/planner/ideas/?site=${activeSite.id}`);
      steps.push({
        name: 'Content Ideas',
        status: ideas.count > 0 ? 'healthy' : 'warning' as const,
        message: `${ideas.count} ideas`,
      });

      // Step 4: Tasks created
      const tasks = await fetchAPI(`/v1/writer/tasks/?site=${activeSite.id}`);
      steps.push({
        name: 'Writer Tasks',
        status: tasks.count > 0 ? 'healthy' : 'warning' as const,
        message: `${tasks.count} tasks`,
      });

      // Step 5: Content generated
      const content = await fetchAPI(`/v1/writer/content/?site=${activeSite.id}`);
      steps.push({
        name: 'Content Generated',
        status: content.count > 0 ? 'healthy' : 'warning' as const,
        message: `${content.count} articles`,
      });

      const hasErrors = steps.some(s => s.status === 'error');
      const hasWarnings = steps.some(s => s.status === 'warning');

      workflows.push({
        name: 'Content Generation Pipeline',
        steps,
        overall: hasErrors ? 'error' : hasWarnings ? 'warning' : 'healthy',
      });
    } catch (error) {
      workflows.push({
        name: 'Content Generation Pipeline',
        steps: [{ name: 'Pipeline Check', status: 'error', message: 'Failed to check workflow' }],
        overall: 'error',
      });
    }

    setWorkflowHealth(workflows);
  }, [activeSite]);

  // Check integration health
  const checkIntegrationHealth = useCallback(async () => {
    if (!activeSite) {
      setIntegrationHealth(null);
      return;
    }

    try {
      const integrations = await fetchAPI(`/v1/integration/integrations/?site_id=${activeSite.id}`);
      
      if (integrations.results && integrations.results.length > 0) {
        const wpIntegration = integrations.results.find((i: any) => i.platform === 'wordpress');
        
        if (wpIntegration) {
          const health = await fetchAPI(`/v1/integration/integrations/${wpIntegration.id}/debug-status/`);
          
          setIntegrationHealth({
            platform: 'WordPress',
            connected: wpIntegration.is_active,
            last_sync: wpIntegration.last_sync_at,
            sync_enabled: wpIntegration.sync_enabled,
            plugin_active: health.health?.plugin_active || false,
            status: wpIntegration.is_active && health.health?.plugin_active ? 'healthy' : 'warning',
          });
        } else {
          setIntegrationHealth(null);
        }
      } else {
        setIntegrationHealth(null);
      }
    } catch (error) {
      console.error('Failed to check integration:', error);
      setIntegrationHealth(null);
    }
  }, [activeSite]);

  // Refresh all data
  const refreshAll = useCallback(async () => {
    setLoading(true);
    await Promise.all([
      fetchSystemMetrics(),
      fetchApiHealth(),
      checkWorkflowHealth(),
      checkIntegrationHealth(),
    ]);
    setLastUpdate(new Date());
    setLoading(false);
  }, [fetchSystemMetrics, fetchApiHealth, checkWorkflowHealth, checkIntegrationHealth]);

  // Initial load and auto-refresh (pause when page not visible)
  useEffect(() => {
    let interval: NodeJS.Timeout;
    
    const handleVisibilityChange = () => {
      if (document.hidden) {
        // Page not visible - clear interval
        if (interval) clearInterval(interval);
      } else {
        // Page visible - refresh and restart interval
        refreshAll();
        interval = setInterval(refreshAll, 30000);
      }
    };
    
    // Initial setup
    refreshAll();
    interval = setInterval(refreshAll, 30000);
    
    // Listen for visibility changes
    document.addEventListener('visibilitychange', handleVisibilityChange);
    
    return () => {
      clearInterval(interval);
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, [refreshAll]);

  // Status badge component
  const StatusBadge = ({ status }: { status: string }) => {
    const colors = {
      healthy: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
      warning: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400',
      error: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
    };
    
    const icons = {
      healthy: CheckCircle,
      warning: AlertTriangle,
      error: XCircle,
    };

    const Icon = icons[status as keyof typeof icons] || AlertTriangle;

    return (
      <div className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${colors[status as keyof typeof colors]}`}>
        <Icon className="h-3 w-3" />
        {status.charAt(0).toUpperCase() + status.slice(1)}
      </div>
    );
  };

  // Progress bar component
  const ProgressBar = ({ value, status }: { value: number; status: string }) => {
    const colors = {
      healthy: 'bg-green-500',
      warning: 'bg-yellow-500',
      error: 'bg-red-500',
    };

    return (
      <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
        <div 
          className={`h-2 rounded-full transition-all ${colors[status as keyof typeof colors]}`}
          style={{ width: `${value}%` }}
        />
      </div>
    );
  };

  return (
    <>
      <PageMeta title="System Status - IGNY8" description="Master status dashboard" />
      
      <div className="space-y-6">
        {/* Header */}
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-2xl font-semibold text-gray-800 dark:text-white/90">System Status</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
              Master dashboard showing all system health metrics
            </p>
          </div>
          <div className="flex items-center gap-4">
            <div className="text-sm text-gray-500 dark:text-gray-400">
              <Clock className="h-4 w-4 inline mr-1" />
              Last updated: {lastUpdate.toLocaleTimeString()}
            </div>
            <button
              onClick={refreshAll}
              disabled={loading}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              <RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
              Refresh
            </button>
          </div>
        </div>

        {/* System Resources & Services Health */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center gap-2">
            <Server className="h-5 w-5 text-blue-600" />
            System Resources
          </h3>
          <div className="flex gap-6">
            {/* Compact System Metrics (70% width) */}
            <div className="flex-1 grid grid-cols-3 gap-4">
              {/* CPU */}
              <div className="bg-gray-50 dark:bg-gray-700/30 rounded p-3">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-1">
                    <Cpu className="h-4 w-4 text-gray-600 dark:text-gray-400" />
                    <span className="text-xs font-medium text-gray-700 dark:text-gray-300">CPU</span>
                  </div>
                  <StatusBadge status={systemMetrics?.cpu.status || 'warning'} />
                </div>
                <div className="text-lg font-bold text-gray-900 dark:text-white">
                  {systemMetrics?.cpu.usage_percent.toFixed(1)}%
                </div>
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">{systemMetrics?.cpu.cores} cores</p>
                <ProgressBar value={systemMetrics?.cpu.usage_percent || 0} status={systemMetrics?.cpu.status || 'warning'} />
              </div>

              {/* Memory */}
              <div className="bg-gray-50 dark:bg-gray-700/30 rounded p-3">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-1">
                    <MemoryStick className="h-4 w-4 text-gray-600 dark:text-gray-400" />
                    <span className="text-xs font-medium text-gray-700 dark:text-gray-300">Memory</span>
                  </div>
                  <StatusBadge status={systemMetrics?.memory.status || 'warning'} />
                </div>
                <div className="text-lg font-bold text-gray-900 dark:text-white">
                  {systemMetrics?.memory.usage_percent.toFixed(1)}%
                </div>
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                  {systemMetrics?.memory.used_gb.toFixed(1)}/{systemMetrics?.memory.total_gb.toFixed(1)} GB
                </p>
                <ProgressBar value={systemMetrics?.memory.usage_percent || 0} status={systemMetrics?.memory.status || 'warning'} />
              </div>

              {/* Disk */}
              <div className="bg-gray-50 dark:bg-gray-700/30 rounded p-3">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-1">
                    <HardDrive className="h-4 w-4 text-gray-600 dark:text-gray-400" />
                    <span className="text-xs font-medium text-gray-700 dark:text-gray-300">Disk</span>
                  </div>
                  <StatusBadge status={systemMetrics?.disk.status || 'warning'} />
                </div>
                <div className="text-lg font-bold text-gray-900 dark:text-white">
                  {systemMetrics?.disk.usage_percent.toFixed(1)}%
                </div>
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                  {systemMetrics?.disk.used_gb.toFixed(1)}/{systemMetrics?.disk.total_gb.toFixed(1)} GB
                </p>
                <ProgressBar value={systemMetrics?.disk.usage_percent || 0} status={systemMetrics?.disk.status || 'warning'} />
              </div>
            </div>

            {/* Services Stack (30% width) */}
            <div className="w-1/3 space-y-2">
              <div className="bg-gray-50 dark:bg-gray-700/30 rounded p-3 flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Database className="h-4 w-4 text-blue-600" />
                  <span className="text-xs font-medium text-gray-700 dark:text-gray-300">PostgreSQL</span>
                </div>
                <StatusBadge status={serviceHealth?.database.status || 'warning'} />
              </div>

              <div className="bg-gray-50 dark:bg-gray-700/30 rounded p-3 flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Zap className="h-4 w-4 text-red-600" />
                  <span className="text-xs font-medium text-gray-700 dark:text-gray-300">Redis</span>
                </div>
                <StatusBadge status={serviceHealth?.redis.status || 'warning'} />
              </div>

              <div className="bg-gray-50 dark:bg-gray-700/30 rounded p-3 flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Activity className="h-4 w-4 text-green-600" />
                  <span className="text-xs font-medium text-gray-700 dark:text-gray-300">Celery</span>
                </div>
                <div className="flex items-center gap-1">
                  <span className="text-xs text-gray-500">{serviceHealth?.celery.worker_count || 0}w</span>
                  <StatusBadge status={serviceHealth?.celery.status || 'warning'} />
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Site Selector */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4 border border-gray-200 dark:border-gray-700">
          <DebugSiteSelector />
        </div>

        {/* API Health by Module */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center gap-2">
            <Zap className="h-5 w-5 text-yellow-600" />
            API Module Health
          </h3>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            {apiHealth.map((group) => (
              <div key={group.name} className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <div className="flex items-center justify-between mb-3">
                  <span className="text-sm font-medium text-gray-700 dark:text-gray-300">{group.name}</span>
                  <StatusBadge status={group.status} />
                </div>
                <div className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
                  {group.percentage}%
                </div>
                <div className="text-xs text-gray-500 dark:text-gray-400 mb-2">
                  {group.healthy}/{group.total} healthy
                </div>
                <ProgressBar value={group.percentage} status={group.status} />
              </div>
            ))}
          </div>
        </div>

        {/* Content Workflow Health */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center gap-2">
            <Workflow className="h-5 w-5 text-purple-600" />
            Content Pipeline Status
          </h3>
          {workflowHealth.length === 0 ? (
            <p className="text-sm text-gray-500 dark:text-gray-400">Select a site to view workflow health</p>
          ) : (
            <div className="space-y-4">
              {workflowHealth.map((workflow) => (
                <div key={workflow.name} className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                  <div className="flex items-center justify-between mb-4">
                    <h4 className="font-medium text-gray-900 dark:text-white">{workflow.name}</h4>
                    <StatusBadge status={workflow.overall} />
                  </div>
                  <div className="flex items-center gap-2">
                    {workflow.steps.map((step, idx) => (
                      <div key={idx} className="flex-1">
                        <div className="flex items-center justify-between mb-1">
                          <span className="text-xs text-gray-600 dark:text-gray-400">{step.name}</span>
                          {step.status === 'healthy' ? (
                            <CheckCircle className="h-3 w-3 text-green-600" />
                          ) : step.status === 'warning' ? (
                            <AlertTriangle className="h-3 w-3 text-yellow-600" />
                          ) : (
                            <XCircle className="h-3 w-3 text-red-600" />
                          )}
                        </div>
                        {step.message && (
                          <p className="text-xs text-gray-500 dark:text-gray-400">{step.message}</p>
                        )}
                        {idx < workflow.steps.length - 1 && (
                          <div className="mt-2 h-1 bg-gray-200 dark:bg-gray-700 rounded">
                            <div className={`h-1 rounded ${
                              step.status === 'healthy' ? 'bg-green-500' : 
                              step.status === 'warning' ? 'bg-yellow-500' : 'bg-red-500'
                            }`} style={{ width: '100%' }} />
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* WordPress Integration */}
        {integrationHealth && (
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
            <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center gap-2">
              <Globe className="h-5 w-5 text-blue-600" />
              WordPress Integration
            </h3>
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
              <div className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <span className="text-sm text-gray-600 dark:text-gray-400 block mb-2">Connection</span>
                <StatusBadge status={integrationHealth.connected ? 'healthy' : 'error'} />
              </div>
              <div className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <span className="text-sm text-gray-600 dark:text-gray-400 block mb-2">Plugin Status</span>
                <StatusBadge status={integrationHealth.plugin_active ? 'healthy' : 'warning'} />
              </div>
              <div className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <span className="text-sm text-gray-600 dark:text-gray-400 block mb-2">Sync Enabled</span>
                <StatusBadge status={integrationHealth.sync_enabled ? 'healthy' : 'warning'} />
              </div>
              <div className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <span className="text-sm text-gray-600 dark:text-gray-400 block mb-2">Last Sync</span>
                <span className="text-sm text-gray-900 dark:text-white">
                  {integrationHealth.last_sync 
                    ? new Date(integrationHealth.last_sync).toLocaleString() 
                    : 'Never'}
                </span>
              </div>
            </div>
          </div>
        )}
      </div>
    </>
  );
}
