import { useState, useEffect } from "react";
import PageMeta from "../../components/common/PageMeta";
import ComponentCard from "../../components/common/ComponentCard";
import { fetchAPI } from "../../services/api";

interface SystemStatus {
  timestamp: string;
  system: {
    cpu: { usage_percent: number; cores: number; status: string };
    memory: { total_gb: number; used_gb: number; available_gb: number; usage_percent: number; status: string };
    disk: { total_gb: number; used_gb: number; free_gb: number; usage_percent: number; status: string };
  };
  database: {
    connected: boolean;
    version: string;
    size: string;
    active_connections: number;
    status: string;
  };
  redis: {
    connected: boolean;
    status: string;
  };
  celery: {
    workers: string[];
    worker_count: number;
    tasks: { active: number; scheduled: number; reserved: number };
    status: string;
  };
  processes: {
    by_stack: {
      [key: string]: { count: number; cpu: number; memory_mb: number };
    };
  };
  modules: {
    planner: { keywords: number; clusters: number; content_ideas: number };
    writer: { tasks: number; images: number };
  };
}

const getStatusColor = (status: string) => {
  switch (status) {
    case 'healthy': return 'text-green-600 dark:text-green-400';
    case 'warning': return 'text-yellow-600 dark:text-yellow-400';
    case 'critical': return 'text-red-600 dark:text-red-400';
    default: return 'text-gray-600 dark:text-gray-400';
  }
};

const getStatusBadge = (status: string) => {
  switch (status) {
    case 'healthy': return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400';
    case 'warning': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400';
    case 'critical': return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400';
    default: return 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-400';
  }
};

export default function Status() {
  const [status, setStatus] = useState<SystemStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchStatus = async () => {
    try {
      const data = await fetchAPI('/v1/system/status/');
      setStatus(data);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStatus();
    const interval = setInterval(fetchStatus, 30000); // Refresh every 30 seconds
    return () => clearInterval(interval);
  }, []);

  if (loading) {
    return (
      <>
        <PageMeta title="System Status - IGNY8" description="System monitoring" />
        <ComponentCard title="System Status" desc="Loading system information...">
          <div className="text-center py-8">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900 dark:border-white mx-auto"></div>
          </div>
        </ComponentCard>
      </>
    );
  }

  if (error || !status) {
    return (
      <>
        <PageMeta title="System Status - IGNY8" description="System monitoring" />
        <ComponentCard title="System Status" desc="Error loading system information">
          <div className="text-center py-8 text-red-600 dark:text-red-400">
            {error || 'Failed to load system status'}
          </div>
        </ComponentCard>
      </>
    );
  }

  return (
    <>
      <PageMeta title="System Status - IGNY8" description="System monitoring" />
      
      <div className="space-y-6">
        {/* System Resources */}
        <ComponentCard title="System Resources" desc="CPU, Memory, and Disk Usage">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {/* CPU */}
            <div className="space-y-2">
              <div className="flex justify-between items-center">
                <span className="text-sm font-medium text-gray-700 dark:text-gray-300">CPU</span>
                <span className={`text-xs px-2 py-1 rounded ${getStatusBadge(status.system?.cpu?.status || 'unknown')}`}>
                  {status.system?.cpu?.status || 'unknown'}
                </span>
              </div>
              <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-4">
                <div
                  className={`h-4 rounded-full ${
                    (status.system?.cpu?.usage_percent || 0) < 80 ? 'bg-green-500' :
                    (status.system?.cpu?.usage_percent || 0) < 95 ? 'bg-yellow-500' : 'bg-red-500'
                  }`}
                  style={{ width: `${status.system?.cpu?.usage_percent || 0}%` }}
                ></div>
              </div>
              <div className="text-sm text-gray-600 dark:text-gray-400">
                {status.system?.cpu?.usage_percent?.toFixed(1)}% used ({status.system?.cpu?.cores} cores)
              </div>
            </div>

            {/* Memory */}
            <div className="space-y-2">
              <div className="flex justify-between items-center">
                <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Memory</span>
                <span className={`text-xs px-2 py-1 rounded ${getStatusBadge(status.system?.memory?.status || 'unknown')}`}>
                  {status.system?.memory?.status || 'unknown'}
                </span>
              </div>
              <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-4">
                <div
                  className={`h-4 rounded-full ${
                    (status.system?.memory?.usage_percent || 0) < 80 ? 'bg-green-500' :
                    (status.system?.memory?.usage_percent || 0) < 95 ? 'bg-yellow-500' : 'bg-red-500'
                  }`}
                  style={{ width: `${status.system?.memory?.usage_percent || 0}%` }}
                ></div>
              </div>
              <div className="text-sm text-gray-600 dark:text-gray-400">
                {status.system?.memory?.used_gb?.toFixed(1)} GB / {status.system?.memory?.total_gb?.toFixed(1)} GB
              </div>
            </div>

            {/* Disk */}
            <div className="space-y-2">
              <div className="flex justify-between items-center">
                <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Disk</span>
                <span className={`text-xs px-2 py-1 rounded ${getStatusBadge(status.system?.disk?.status || 'unknown')}`}>
                  {status.system?.disk?.status || 'unknown'}
                </span>
              </div>
              <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-4">
                <div
                  className={`h-4 rounded-full ${
                    (status.system?.disk?.usage_percent || 0) < 80 ? 'bg-green-500' :
                    (status.system?.disk?.usage_percent || 0) < 95 ? 'bg-yellow-500' : 'bg-red-500'
                  }`}
                  style={{ width: `${status.system?.disk?.usage_percent || 0}%` }}
                ></div>
              </div>
              <div className="text-sm text-gray-600 dark:text-gray-400">
                {status.system?.disk?.used_gb?.toFixed(1)} GB / {status.system?.disk?.total_gb?.toFixed(1)} GB
              </div>
            </div>
          </div>
        </ComponentCard>

        {/* Services Status */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {/* Database */}
          <ComponentCard title="Database" desc="PostgreSQL Status">
            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <span className="text-sm text-gray-600 dark:text-gray-400">Status</span>
                <span className={`text-xs px-2 py-1 rounded ${getStatusBadge(status.database?.status || 'unknown')}`}>
                  {status.database?.connected ? 'Connected' : 'Disconnected'}
                </span>
              </div>
              {status.database?.version && (
                <div className="text-sm">
                  <span className="text-gray-600 dark:text-gray-400">Version:</span>
                  <span className="ml-2 text-gray-800 dark:text-gray-200">{status.database.version.split(',')[0]}</span>
                </div>
              )}
              {status.database?.size && (
                <div className="text-sm">
                  <span className="text-gray-600 dark:text-gray-400">Size:</span>
                  <span className="ml-2 text-gray-800 dark:text-gray-200">{status.database.size}</span>
                </div>
              )}
              <div className="text-sm">
                <span className="text-gray-600 dark:text-gray-400">Active Connections:</span>
                <span className="ml-2 text-gray-800 dark:text-gray-200">{status.database?.active_connections || 0}</span>
              </div>
            </div>
          </ComponentCard>

          {/* Redis */}
          <ComponentCard title="Redis" desc="Cache & Message Broker">
            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <span className="text-sm text-gray-600 dark:text-gray-400">Status</span>
                <span className={`text-xs px-2 py-1 rounded ${getStatusBadge(status.redis?.status || 'unknown')}`}>
                  {status.redis?.connected ? 'Connected' : 'Disconnected'}
                </span>
              </div>
            </div>
          </ComponentCard>

          {/* Celery */}
          <ComponentCard title="Celery" desc="Task Queue Workers">
            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <span className="text-sm text-gray-600 dark:text-gray-400">Workers</span>
                <span className={`text-xs px-2 py-1 rounded ${getStatusBadge(status.celery?.status || 'unknown')}`}>
                  {status.celery?.worker_count || 0} active
                </span>
              </div>
              <div className="text-sm">
                <span className="text-gray-600 dark:text-gray-400">Active Tasks:</span>
                <span className="ml-2 text-gray-800 dark:text-gray-200">{status.celery?.tasks?.active || 0}</span>
              </div>
              <div className="text-sm">
                <span className="text-gray-600 dark:text-gray-400">Scheduled:</span>
                <span className="ml-2 text-gray-800 dark:text-gray-200">{status.celery?.tasks?.scheduled || 0}</span>
              </div>
              <div className="text-sm">
                <span className="text-gray-600 dark:text-gray-400">Reserved:</span>
                <span className="ml-2 text-gray-800 dark:text-gray-200">{status.celery?.tasks?.reserved || 0}</span>
              </div>
            </div>
          </ComponentCard>
        </div>

        {/* Process Monitoring by Stack */}
        <ComponentCard title="Process Monitoring" desc="Resource usage by technology stack">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
              <thead>
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Stack</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Processes</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">CPU %</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Memory (MB)</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                {Object.entries(status.processes?.by_stack || {}).map(([stack, stats]) => (
                  <tr key={stack}>
                    <td className="px-4 py-3 text-sm font-medium text-gray-800 dark:text-gray-200 capitalize">{stack}</td>
                    <td className="px-4 py-3 text-sm text-gray-600 dark:text-gray-400">{stats.count}</td>
                    <td className="px-4 py-3 text-sm text-gray-600 dark:text-gray-400">{stats.cpu.toFixed(2)}%</td>
                    <td className="px-4 py-3 text-sm text-gray-600 dark:text-gray-400">{stats.memory_mb.toFixed(2)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </ComponentCard>

        {/* Module Statistics */}
        <ComponentCard title="Module Statistics" desc="Data counts by module">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* Planner Module */}
            <div className="space-y-3">
              <h4 className="text-sm font-semibold text-gray-800 dark:text-gray-200">Planner Module</h4>
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">Keywords:</span>
                  <span className="text-gray-800 dark:text-gray-200">{status.modules?.planner?.keywords?.toLocaleString() || 0}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">Clusters:</span>
                  <span className="text-gray-800 dark:text-gray-200">{status.modules?.planner?.clusters?.toLocaleString() || 0}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">Content Ideas:</span>
                  <span className="text-gray-800 dark:text-gray-200">{status.modules?.planner?.content_ideas?.toLocaleString() || 0}</span>
                </div>
              </div>
            </div>

            {/* Writer Module */}
            <div className="space-y-3">
              <h4 className="text-sm font-semibold text-gray-800 dark:text-gray-200">Writer Module</h4>
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">Tasks:</span>
                  <span className="text-gray-800 dark:text-gray-200">{status.modules?.writer?.tasks?.toLocaleString() || 0}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">Images:</span>
                  <span className="text-gray-800 dark:text-gray-200">{status.modules?.writer?.images?.toLocaleString() || 0}</span>
                </div>
              </div>
            </div>
          </div>
        </ComponentCard>

        {/* Last Updated */}
        <div className="text-center text-sm text-gray-500 dark:text-gray-400">
          Last updated: {new Date(status.timestamp).toLocaleString()}
        </div>
      </div>
    </>
  );
}
