import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { Cpu, HardDrive, Wifi, Server, RefreshCw } from 'lucide-react';
import { Card } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import { Button } from '@/components/ui/Button';
import { ProgressBar } from '@/components/ui/ProgressBar';
import { SkeletonCard } from '@/components/ui/Skeleton';
import { ownerAPI } from '@/api/client';
import { useSSE } from '@/hooks/useSSE';
import { staggerContainer, staggerItem } from '@/lib/animations';

export default function SystemOverview() {
  const [system, setSystem] = useState<any>(null);
  const [containers, setContainers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([
      ownerAPI.getSystem().then(({ data }) => setSystem(data)),
      ownerAPI.getContainers().then(({ data }) => setContainers(data.containers || [])),
    ]).catch(() => {}).finally(() => setLoading(false));
  }, []);

  useSSE('/owner/system/stream', {
    enabled: !loading,
    onMessage: (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.system) setSystem(data.system);
        if (data.containers) setContainers(data.containers);
      } catch {}
    },
  });

  if (loading) {
    return (
      <div className="p-6 space-y-4">
        <div className="grid grid-cols-4 gap-4">{[...Array(4)].map((_, i) => <SkeletonCard key={i} />)}</div>
        <SkeletonCard />
      </div>
    );
  }

  const metrics = [
    { icon: Cpu, label: 'CPU', value: `${system?.cpu_percent || 0}%`, progress: system?.cpu_percent || 0, color: 'amber' as const },
    { icon: HardDrive, label: 'RAM', value: `${system?.ram_used || 0}/${system?.ram_total || 0}GB`, progress: system?.ram_percent || 0, color: 'blue' as const },
    { icon: HardDrive, label: 'Disk', value: `${system?.disk_used || 0}/${system?.disk_total || 0}GB`, progress: system?.disk_percent || 0, color: 'green' as const },
    { icon: Wifi, label: 'Network', value: `${system?.network_mbps || 0} Mbps`, progress: Math.min((system?.network_mbps || 0) / 100 * 100, 100), color: 'amber' as const },
  ];

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-xl font-bold text-text-primary">System Overview</h1>
        <Badge variant="success" dot>All Systems OK</Badge>
      </div>

      <motion.div variants={staggerContainer} initial="initial" animate="animate" className="space-y-6">
        <motion.div variants={staggerItem} className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {metrics.map((m) => (
            <Card key={m.label}>
              <div className="flex items-center gap-2 mb-2">
                <m.icon className="w-4 h-4 text-text-muted" />
                <span className="text-xs text-text-muted uppercase tracking-wider">{m.label}</span>
              </div>
              <p className="text-2xl font-mono font-bold text-text-primary mb-2">{m.value}</p>
              <ProgressBar value={m.progress} color={m.color} />
            </Card>
          ))}
        </motion.div>

        <motion.div variants={staggerItem}>
          <Card padding={false}>
            <div className="px-5 py-3 border-b border-white/[0.06] flex items-center justify-between">
              <h2 className="text-sm font-bold text-text-muted uppercase tracking-widest">Services</h2>
              <Button variant="ghost" size="sm" onClick={() => window.location.reload()}>
                <RefreshCw className="w-3.5 h-3.5" /> Refresh
              </Button>
            </div>
            <div className="divide-y divide-white/[0.03]">
              {containers.map((c: any) => (
                <div key={c.id || c.name} className="flex items-center gap-4 px-5 py-3">
                  <Server className="w-4 h-4 text-text-muted" />
                  <span className="text-sm font-medium text-text-primary flex-1">{c.name}</span>
                  <Badge variant={c.status === 'running' ? 'success' : 'danger'} dot>
                    {c.status || 'unknown'}
                  </Badge>
                  <span className="text-xs font-mono text-text-muted w-16 text-right">{c.cpu || '-'}</span>
                  <span className="text-xs font-mono text-text-muted w-20 text-right">{c.memory || '-'}</span>
                  <span className="text-xs text-text-muted w-20 text-right">{c.uptime || '-'}</span>
                </div>
              ))}
              {containers.length === 0 && (
                <p className="px-5 py-8 text-center text-sm text-text-muted">No containers found</p>
              )}
            </div>
          </Card>
        </motion.div>
      </motion.div>
    </div>
  );
}
