import { useQuery } from '@tanstack/react-query';
import { Database, HardDrive, Layers, AlertCircle, Activity, Cpu } from 'lucide-react';
import { api } from '../../lib/api-client';
import { AppShell, PageHeader, PageBody } from '../../layout/AppShell';
import { Badge, Card } from '../../components/ui/primitives';

interface Health {
  pool: { total: number; idle: number; waiting: number };
  db: {
    products: string;
    offers: string;
    active_feeds: string;
    db_size: string;
    subscribers: string;
  };
  queue: { pending: number; running: number; completed: number; failed: number; cancelled: number; total: number };
  errors_24h: Array<{ severity: string; count: string }>;
  largest_tables: Array<{ table_name: string; size: string; size_bytes: number }>;
  uptime_seconds: number;
  memory_mb: number;
  node_version: string;
}

function formatUptime(secs: number): string {
  const d = Math.floor(secs / 86400);
  const h = Math.floor((secs % 86400) / 3600);
  const m = Math.floor((secs % 3600) / 60);
  if (d > 0) return `${d}d ${h}h`;
  if (h > 0) return `${h}h ${m}m`;
  return `${m}m`;
}

export function SystemHealth() {
  const { data } = useQuery({
    queryKey: ['health'],
    queryFn: () => api.get<Health>('/health'),
    refetchInterval: 10000,
  });

  if (!data) {
    return (
      <AppShell>
        <PageHeader title="System health" description="Database, queue, disk, errors." />
        <PageBody>
          <div className="text-sm text-[#999]">Laden...</div>
        </PageBody>
      </AppShell>
    );
  }

  const errors24 = data.errors_24h.reduce((sum, e) => sum + parseInt(e.count, 10), 0);
  const allOk = errors24 === 0 && data.queue.failed === 0 && data.pool.waiting === 0;

  return (
    <AppShell>
      <PageHeader
        title="System health"
        description="Database, queue, disk, errors."
        actions={
          <Badge variant={allOk ? 'success' : 'warn'}>
            {allOk ? 'Alles gezond' : 'Controleer onderdelen'}
          </Badge>
        }
      />
      <PageBody>
        <div className="grid grid-cols-4 gap-4 mb-4">
          <StatBlock
            icon={<Activity className="h-4 w-4" />}
            label="Uptime"
            value={formatUptime(data.uptime_seconds)}
            hint={data.node_version}
          />
          <StatBlock
            icon={<Cpu className="h-4 w-4" />}
            label="Memory"
            value={`${data.memory_mb} MB`}
            hint="heap used"
          />
          <StatBlock
            icon={<Database className="h-4 w-4" />}
            label="DB size"
            value={data.db.db_size}
            hint={`${Number(data.db.products).toLocaleString('nl-NL')} producten`}
          />
          <StatBlock
            icon={<AlertCircle className="h-4 w-4" />}
            label="Errors (24u)"
            value={String(errors24)}
            hint={errors24 === 0 ? 'Geen fouten' : 'Zie error log'}
            danger={errors24 > 0}
          />
        </div>

        <div className="grid grid-cols-2 gap-4 mb-4">
          <Card>
            <div className="px-5 py-3 border-b border-[#333] flex items-center gap-2">
              <Database className="h-4 w-4 text-[#999]" />
              <h3 className="text-sm font-semibold text-[#F5F5F5]">Connection pool</h3>
            </div>
            <div className="px-5 py-4 space-y-2 text-sm">
              <Row label="Totaal">{data.pool.total}</Row>
              <Row label="Idle">{data.pool.idle}</Row>
              <Row label="In gebruik">{data.pool.total - data.pool.idle}</Row>
              <Row label="Wachtend" danger={data.pool.waiting > 0}>
                {data.pool.waiting}
              </Row>
            </div>
          </Card>

          <Card>
            <div className="px-5 py-3 border-b border-[#333] flex items-center gap-2">
              <Layers className="h-4 w-4 text-[#999]" />
              <h3 className="text-sm font-semibold text-[#F5F5F5]">Job queue</h3>
            </div>
            <div className="px-5 py-4 space-y-2 text-sm">
              <Row label="Pending">{data.queue.pending}</Row>
              <Row label="Running">{data.queue.running}</Row>
              <Row label="Completed">{data.queue.completed}</Row>
              <Row label="Failed" danger={data.queue.failed > 0}>
                {data.queue.failed}
              </Row>
            </div>
          </Card>
        </div>

        <Card>
          <div className="px-5 py-3 border-b border-[#333] flex items-center gap-2">
            <HardDrive className="h-4 w-4 text-[#999]" />
            <h3 className="text-sm font-semibold text-[#F5F5F5]">Top 10 grootste tabellen</h3>
          </div>
          <div className="divide-y divide-[#222]">
            {data.largest_tables.map((t) => {
              const pct = Math.max(2, Math.round((t.size_bytes / data.largest_tables[0].size_bytes) * 100));
              return (
                <div key={t.table_name} className="px-5 py-2.5 flex items-center gap-4">
                  <div className="w-56 text-sm font-mono">{t.table_name}</div>
                  <div className="flex-1 h-1.5 bg-[#1A1A1A] rounded-full overflow-hidden">
                    <div className="h-full bg-[#00FF6A]/60" style={{ width: `${pct}%` }} />
                  </div>
                  <div className="w-24 text-right text-xs text-[#999] font-mono">{t.size}</div>
                </div>
              );
            })}
          </div>
        </Card>
      </PageBody>
    </AppShell>
  );
}

function StatBlock({
  icon,
  label,
  value,
  hint,
  danger,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  hint: string;
  danger?: boolean;
}) {
  return (
    <Card className="px-4 py-3">
      <div className="flex items-start justify-between">
        <div>
          <p className="text-xs text-[#999]">{label}</p>
          <p className={`text-2xl font-semibold mt-0.5 ${danger ? 'text-[#FF3B3B]' : 'text-[#F5F5F5]'}`}>
            {value}
          </p>
          <p className="text-[11px] text-[#666] mt-0.5">{hint}</p>
        </div>
        <div className="text-[#666]">{icon}</div>
      </div>
    </Card>
  );
}

function Row({ label, children, danger }: { label: string; children: React.ReactNode; danger?: boolean }) {
  return (
    <div className="flex items-center justify-between">
      <span className="text-xs text-[#999]">{label}</span>
      <span className={`font-mono text-sm ${danger ? 'text-[#FF3B3B]' : 'text-[#F5F5F5]'}`}>{children}</span>
    </div>
  );
}
