'use client';

import { useEffect, useState } from 'react';
import { apiRequest } from '@/lib/api';
import { formatBytes } from '@/lib/utils';
import { Cpu, HardDrive, Database, Trash2, RefreshCw, AlertTriangle, CheckCircle } from 'lucide-react';
import { SidebarNav } from '@/components/sidebar-nav';

interface SystemMetrics {
  timestamp: string;
  uptime: string;
  cpu: {
    usage: number;
    cores: number;
    loadAverage: number[];
  };
  memory: {
    total: number;
    used: number;
    free: number;
    percentage: number;
  };
  disk: Array<{
    path: string;
    total: number;
    used: number;
    free: number;
    percentage: number;
  }>;
  platform: {
    nodeVersion: string;
    platform: string;
    arch: string;
    hostname: string;
  };
}

interface DockerStats {
  images: {
    total: number;
    dangling: number;
    size: number;
  };
  containers: {
    total: number;
    running: number;
    stopped: number;
    size: number;
  };
  volumes: {
    total: number;
    unused: number;
    size: number;
  };
}

export default function SystemPage() {
  const [metrics, setMetrics] = useState<SystemMetrics | null>(null);
  const [dockerStats, setDockerStats] = useState<DockerStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [cleanupResult, setCleanupResult] = useState<{ message: string; freedSpace: number } | null>(null);

  const loadData = async () => {
    try {
      const [metricsData, dockerData] = await Promise.all([
        apiRequest<SystemMetrics>('/api/system/metrics'),
        apiRequest<DockerStats>('/api/docker/stats'),
      ]);
      setMetrics(metricsData);
      setDockerStats(dockerData);
    } catch (error) {
      console.error('Failed to load system data:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

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

  const handleRefresh = () => {
    setRefreshing(true);
    loadData();
  };

  const handleCleanup = async (type: string, force: boolean = false) => {
    if (!confirm(`Are you sure you want to clean up Docker ${type}?${force ? ' This will force remove all unused items.' : ''}`)) {
      return;
    }

    try {
      const result = await apiRequest<{ message: string; freedSpace: number }>('/api/docker/cleanup', {
        method: 'POST',
        body: JSON.stringify({ type, force }),
      });
      setCleanupResult(result);
      loadData();
    } catch (error) {
      console.error('Cleanup failed:', error);
      alert('Cleanup failed');
    }
  };

  const getUsageColor = (percentage: number): string => {
    if (percentage < 50) return 'text-green-600 bg-green-50';
    if (percentage < 75) return 'text-yellow-600 bg-yellow-50';
    return 'text-red-600 bg-red-50';
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-gray-600">Loading...</div>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen bg-gray-50">
      <SidebarNav />

      <main className="flex-1 min-w-0 overflow-y-auto">
        <div className="p-8 max-md:p-4">
          <div className="mb-8 flex items-center justify-between">
            <div>
              <h1 className="text-2xl font-bold text-gray-900">System Management</h1>
              <p className="text-sm text-gray-600">Monitor resources and manage Docker</p>
            </div>
            <button
              onClick={handleRefresh}
              disabled={refreshing}
              className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
              aria-label="Refresh system metrics"
            >
              <RefreshCw className={`w-4 h-4 ${refreshing ? 'animate-spin' : ''}`} />
              Refresh
            </button>
          </div>
        {cleanupResult && (
          <div className="bg-green-50 border border-green-200 rounded-lg p-4 flex items-center gap-3">
            <CheckCircle className="w-5 h-5 text-green-600" />
            <div>
              <p className="font-medium text-green-900">{cleanupResult.message}</p>
              <p className="text-sm text-green-700">Freed space: {formatBytes(cleanupResult.freedSpace * 1024 * 1024)}</p>
            </div>
            <button
              onClick={() => setCleanupResult(null)}
              className="ml-auto text-green-600 hover:text-green-800"
            >
              Dismiss
            </button>
          </div>
        )}

        {/* System Metrics */}
        <div className="bg-white border border-gray-200 rounded-lg p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-6">System Metrics</h2>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            {/* CPU */}
            <div className="border border-gray-200 rounded-lg p-4">
              <div className="flex items-center gap-3 mb-3">
                <Cpu className="w-5 h-5 text-blue-600" />
                <div>
                  <p className="text-sm font-medium text-gray-500">CPU Usage</p>
                  <p className="text-2xl font-bold text-gray-900">{metrics?.cpu.usage || 0}%</p>
                </div>
              </div>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-gray-600">Cores</span>
                  <span className="font-medium">{metrics?.cpu.cores || 0}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Load Avg (1m)</span>
                  <span className="font-medium">{metrics?.cpu.loadAverage[0]?.toFixed(2) || '0.00'}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Load Avg (5m)</span>
                  <span className="font-medium">{metrics?.cpu.loadAverage[1]?.toFixed(2) || '0.00'}</span>
                </div>
              </div>
            </div>

            {/* Memory */}
            <div className="border border-gray-200 rounded-lg p-4">
              <div className="flex items-center gap-3 mb-3">
                <Database className="w-5 h-5 text-purple-600" />
                <div>
                  <p className="text-sm font-medium text-gray-500">Memory</p>
                  <p className="text-2xl font-bold text-gray-900">{metrics?.memory.percentage || 0}%</p>
                </div>
              </div>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-gray-600">Total</span>
                  <span className="font-medium">{formatBytes((metrics?.memory.total || 0) * 1024 * 1024 * 1024)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Used</span>
                  <span className="font-medium">{formatBytes((metrics?.memory.used || 0) * 1024 * 1024 * 1024)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Free</span>
                  <span className="font-medium">{formatBytes((metrics?.memory.free || 0) * 1024 * 1024 * 1024)}</span>
                </div>
              </div>
              <div className="mt-3">
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div
                    className={`h-2 rounded-full ${getUsageColor(metrics?.memory.percentage || 0).split(' ')[1]}`}
                    style={{ width: `${metrics?.memory.percentage || 0}%` }}
                  />
                </div>
              </div>
            </div>

            {/* Disk */}
            <div className="border border-gray-200 rounded-lg p-4">
              <div className="flex items-center gap-3 mb-3">
                <HardDrive className="w-5 h-5 text-orange-600" />
                <div>
                  <p className="text-sm font-medium text-gray-500">Disk Usage</p>
                </div>
              </div>
              <div className="space-y-3">
                {metrics?.disk.map((disk) => (
                  <div key={disk.path}>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-gray-600">{disk.path}</span>
                      <span className="font-medium">{disk.percentage}%</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div
                        className={`h-2 rounded-full ${getUsageColor(disk.percentage).split(' ')[1]}`}
                        style={{ width: `${disk.percentage}%` }}
                      />
                    </div>
                    <div className="flex justify-between text-xs text-gray-500 mt-1">
                      <span>{formatBytes(disk.used)} used</span>
                      <span>{formatBytes(disk.free)} free</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Platform Info */}
          <div className="border-t border-gray-200 pt-4">
            <h3 className="text-sm font-medium text-gray-500 mb-2">Platform Information</h3>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
              <div>
                <span className="text-gray-500">Hostname</span>
                <p className="font-medium">{metrics?.platform.hostname || 'N/A'}</p>
              </div>
              <div>
                <span className="text-gray-500">Platform</span>
                <p className="font-medium">{metrics?.platform.platform || 'N/A'}</p>
              </div>
              <div>
                <span className="text-gray-500">Architecture</span>
                <p className="font-medium">{metrics?.platform.arch || 'N/A'}</p>
              </div>
              <div>
                <span className="text-gray-500">Node Version</span>
                <p className="font-medium">{metrics?.platform.nodeVersion || 'N/A'}</p>
              </div>
            </div>
          </div>
        </div>

        {/* Docker Management */}
        <div className="bg-white border border-gray-200 rounded-lg p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-6">Docker Management</h2>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            {/* Images */}
            <div className="border border-gray-200 rounded-lg p-4">
              <div className="flex items-center justify-between mb-3">
                <h3 className="font-medium text-gray-900">Images</h3>
                <Database className="w-5 h-5 text-blue-600" />
              </div>
              <div className="space-y-2 text-sm mb-4">
                <div className="flex justify-between">
                  <span className="text-gray-600">Total</span>
                  <span className="font-medium">{dockerStats?.images.total || 0}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Dangling</span>
                  <span className="font-medium">{dockerStats?.images.dangling || 0}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Size</span>
                  <span className="font-medium">{formatBytes(dockerStats?.images.size || 0)}</span>
                </div>
              </div>
              <div className="flex gap-2">
                <button
                  onClick={() => handleCleanup('images', false)}
                  className="flex-1 px-3 py-2 text-sm font-medium text-blue-600 bg-blue-50 border border-blue-200 rounded hover:bg-blue-100"
                >
                  Prune
                </button>
                <button
                  onClick={() => handleCleanup('images', true)}
                  className="flex-1 px-3 py-2 text-sm font-medium text-red-600 bg-red-50 border border-red-200 rounded hover:bg-red-100"
                >
                  Force Prune
                </button>
              </div>
            </div>

            {/* Containers */}
            <div className="border border-gray-200 rounded-lg p-4">
              <div className="flex items-center justify-between mb-3">
                <h3 className="font-medium text-gray-900">Containers</h3>
                <Database className="w-5 h-5 text-green-600" />
              </div>
              <div className="space-y-2 text-sm mb-4">
                <div className="flex justify-between">
                  <span className="text-gray-600">Total</span>
                  <span className="font-medium">{dockerStats?.containers.total || 0}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Running</span>
                  <span className="font-medium text-green-600">{dockerStats?.containers.running || 0}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Stopped</span>
                  <span className="font-medium text-red-600">{dockerStats?.containers.stopped || 0}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Size</span>
                  <span className="font-medium">{formatBytes(dockerStats?.containers.size || 0)}</span>
                </div>
              </div>
              <button
                onClick={() => handleCleanup('containers', false)}
                className="w-full px-3 py-2 text-sm font-medium text-blue-600 bg-blue-50 border border-blue-200 rounded hover:bg-blue-100"
              >
                Prune Stopped
              </button>
            </div>

            {/* Volumes */}
            <div className="border border-gray-200 rounded-lg p-4">
              <div className="flex items-center justify-between mb-3">
                <h3 className="font-medium text-gray-900">Volumes</h3>
                <Database className="w-5 h-5 text-purple-600" />
              </div>
              <div className="space-y-2 text-sm mb-4">
                <div className="flex justify-between">
                  <span className="text-gray-600">Total</span>
                  <span className="font-medium">{dockerStats?.volumes.total || 0}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Unused</span>
                  <span className="font-medium">{dockerStats?.volumes.unused || 0}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Size</span>
                  <span className="font-medium">{formatBytes(dockerStats?.volumes.size || 0)}</span>
                </div>
              </div>
              <button
                onClick={() => handleCleanup('volumes', false)}
                className="w-full px-3 py-2 text-sm font-medium text-blue-600 bg-blue-50 border border-blue-200 rounded hover:bg-blue-100"
              >
                Prune Unused
              </button>
            </div>
          </div>

          {/* Full Cleanup */}
          <div className="border-t border-gray-200 pt-4">
            <div className="flex items-center gap-3 mb-3">
              <AlertTriangle className="w-5 h-5 text-orange-600" />
              <div>
                <h3 className="font-medium text-gray-900">Full Cleanup</h3>
                <p className="text-sm text-gray-500">Remove all unused Docker resources (images, containers, volumes, build cache)</p>
              </div>
            </div>
            <button
              onClick={() => handleCleanup('all', true)}
              className="px-4 py-2 text-sm font-medium text-red-600 bg-red-50 border border-red-200 rounded hover:bg-red-100"
            >
              <Trash2 className="w-4 h-4 inline mr-2" />
              Run Full Cleanup
            </button>
          </div>
        </div>
      </div>
    </main>
    </div>
  );
}
