'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  Activity,
  CheckCircle,
  Database,
  ExternalLink,
  HardDrive,
  Loader2,
  RefreshCw,
  Search,
  ServerCog,
  ShieldAlert,
} from 'lucide-react';
import { buildOpsCockpit } from '@/lib/ops-cockpit';

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

interface ServiceCheck {
  id: string;
  name: string;
  group: string;
  target: string;
  status: 'healthy' | 'degraded' | 'down' | 'maintenance';
  latency: number;
  version?: string;
  message?: string;
  lastChecked: string;
}

interface OpsStatus {
  overall: 'healthy' | 'degraded' | 'critical';
  timestamp: string;
  services: ServiceCheck[];
}

interface InventoryService extends ServiceCheck {
  description: string;
  management: 'docker' | 'vm';
  exposure: 'internal' | 'public';
  port?: number;
  restartable: boolean;
}

interface HostTool {
  id: string;
  name: string;
  group: string;
  source: 'docker' | 'vm';
  management: string;
  status: 'managed' | 'manual';
  description: string;
}

interface InventoryData {
  timestamp: string;
  counts: {
    services: number;
    healthy: number;
    degraded: number;
    down: number;
    hostTools: number;
  };
  services: InventoryService[];
  hostTools: HostTool[];
}

interface ValkeyKey {
  key: string;
  type: string;
  ttlSeconds: number;
  size?: number;
  preview?: string;
}

interface ValkeyData {
  timestamp: string;
  pattern: string;
  limit: number;
  summary: {
    ping: string;
    dbsize: number;
    matchedKeys: number;
    version: string;
    usedMemoryHuman: string;
    usedMemoryPeakHuman: string;
  };
  keys: ValkeyKey[];
}

const OPS_LINKS = [
  { label: 'Grafana', href: 'http://127.0.0.1:3000' },
  { label: 'Prometheus', href: 'http://127.0.0.1:9090' },
  { label: 'Loki Ready', href: 'http://127.0.0.1:3100/ready' },
  { label: 'Admin Health', href: 'http://127.0.0.1:3001/api/health' },
  { label: 'Tracker Health', href: 'http://127.0.0.1:3003/api/health' },
  { label: 'API Gateway Health', href: 'https://api.bytelyst.com/platform/health' },
];

export default function OpsPage() {
  const [data, setData] = useState<OpsStatus | null>(null);
  const [inventory, setInventory] = useState<InventoryData | null>(null);
  const [valkey, setValkey] = useState<ValkeyData | null>(null);
  const [loading, setLoading] = useState(true);
  const [valkeyLoading, setValkeyLoading] = useState(true);
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
  const [_error, setError] = useState<string | null>(null);
  const [countdown, setCountdown] = useState(10);
  const [activeTab, setActiveTab] = useState<'overview' | 'inventory' | 'valkey'>('overview');
  const [valkeyPattern, setValkeyPattern] = useState('*');
  const [valkeyLimit, setValkeyLimit] = useState('25');
  const [actionMessage, setActionMessage] = useState<string | null>(null);
  const [pendingRestart, setPendingRestart] = useState<string | null>(null);
  const [pendingDelete, setPendingDelete] = useState<string | null>(null);

  const fetchValkey = useCallback(
    async (pattern = valkeyPattern, limit = valkeyLimit) => {
      try {
        setValkeyLoading(true);
        const params = new URLSearchParams({
          pattern,
          limit,
        });
        const res = await fetch(`/api/ops/valkey?${params.toString()}`);
        if (!res.ok) throw new Error('Failed to fetch Valkey state');
        setValkey(await res.json());
      } finally {
        setValkeyLoading(false);
      }
    },
    [valkeyLimit, valkeyPattern]
  );

  const fetchStatus = useCallback(async () => {
    try {
      setLoading(true);
      const [statusRes, inventoryRes] = await Promise.all([
        fetch('/api/ops/status'),
        fetch('/api/ops/inventory'),
      ]);

      if (!statusRes.ok) throw new Error('Failed to fetch status');
      if (!inventoryRes.ok) throw new Error('Failed to fetch inventory');

      const [statusJson, inventoryJson] = await Promise.all([
        statusRes.json(),
        inventoryRes.json(),
      ]);
      setData(statusJson);
      setInventory(inventoryJson);
      setLastUpdated(new Date());
      setError(null);
      await fetchValkey();
    } catch (err) {
      setError(String(err));
    } finally {
      setLoading(false);
      setCountdown(10);
    }
  }, [fetchValkey]);

  const restartService = async (serviceId: string) => {
    try {
      setPendingRestart(serviceId);
      setActionMessage(null);
      const res = await fetch('/api/ops/control', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'restart', serviceId }),
      });
      const payload = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(payload.error || 'Restart failed');
      setActionMessage(`Restart requested for ${serviceId}`);
      await fetchStatus();
    } catch (error) {
      setActionMessage(error instanceof Error ? error.message : 'Restart failed');
    } finally {
      setPendingRestart(null);
    }
  };

  const deleteValkeyKey = async (key: string) => {
    try {
      setPendingDelete(key);
      setActionMessage(null);
      const res = await fetch('/api/ops/valkey', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'deleteKey', key }),
      });
      const payload = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(payload.error || 'Delete failed');
      setActionMessage(`Deleted key ${key}`);
      await fetchValkey();
    } catch (error) {
      setActionMessage(error instanceof Error ? error.message : 'Delete failed');
    } finally {
      setPendingDelete(null);
    }
  };

  const deleteValkeyPattern = async () => {
    try {
      const marker = `pattern:${valkeyPattern}`;
      setPendingDelete(marker);
      setActionMessage(null);
      const res = await fetch('/api/ops/valkey', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'deletePattern',
          pattern: valkeyPattern,
          limit: Number(valkeyLimit || '25'),
        }),
      });
      const payload = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(payload.error || 'Pattern delete failed');
      setActionMessage(`Deleted ${payload.deleted || 0} keys for pattern ${valkeyPattern}`);
      await fetchValkey();
    } catch (error) {
      setActionMessage(error instanceof Error ? error.message : 'Pattern delete failed');
    } finally {
      setPendingDelete(null);
    }
  };

  useEffect(() => {
    void fetchStatus();
    const timer = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          void fetchStatus();
          return 10;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [fetchStatus]);

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'healthy':
        return 'bg-green-500/10 text-green-500 hover:bg-green-500/20';
      case 'degraded':
        return 'bg-yellow-500/10 text-yellow-500 hover:bg-yellow-500/20';
      case 'down':
        return 'bg-red-500/10 text-red-500 hover:bg-red-500/20';
      default:
        return 'bg-gray-500/10 text-gray-500';
    }
  };

  const getLatencyColor = (ms: number) => {
    if (ms < 100) return 'text-green-500';
    if (ms < 500) return 'text-yellow-500';
    return 'text-red-500';
  };

  const cockpit = useMemo(
    () => buildOpsCockpit({ status: data, inventory, valkey }),
    [data, inventory, valkey]
  );

  const getTileColor = (tone: string) => {
    switch (tone) {
      case 'success':
        return 'text-green-600';
      case 'warning':
        return 'text-yellow-600';
      case 'danger':
        return 'text-red-600';
      default:
        return 'text-muted-foreground';
    }
  };

  const getActionColor = (severity: string) => {
    switch (severity) {
      case 'critical':
        return 'border-red-200 bg-red-50 text-red-900 dark:border-red-900/50 dark:bg-red-950/20 dark:text-red-100';
      case 'warning':
        return 'border-yellow-200 bg-yellow-50 text-yellow-900 dark:border-yellow-900/50 dark:bg-yellow-950/20 dark:text-yellow-100';
      default:
        return 'border-border bg-muted/40';
    }
  };

  return (
    <div className="flex-1 space-y-4 p-8 pt-6">
      <div className="flex items-center justify-between space-y-2">
        <h2 className="text-3xl font-bold tracking-tight">Mission Control</h2>
        <div className="flex items-center space-x-2">
          <Button variant="outline" size="sm" onClick={() => fetchStatus()}>
            <RefreshCw className={`mr-2 h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
            Refresh ({countdown}s)
          </Button>
        </div>
      </div>

      {data && (
        <Card
          className={`border-l-4 ${data.overall === 'healthy' ? 'border-l-green-500' : data.overall === 'degraded' ? 'border-l-yellow-500' : 'border-l-red-500'}`}
        >
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Global System Status</CardTitle>
            {data.overall === 'healthy' ? (
              <CheckCircle className="h-4 w-4 text-green-500" />
            ) : (
              <ShieldAlert className="h-4 w-4 text-red-500" />
            )}
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold capitalize">{data.overall}</div>
            <p className="text-xs text-muted-foreground">
              Last updated: {lastUpdated?.toLocaleTimeString()}
            </p>
          </CardContent>
        </Card>
      )}

      {actionMessage && (
        <Card>
          <CardContent className="py-4 text-sm">{actionMessage}</CardContent>
        </Card>
      )}

      <Card>
        <CardHeader>
          <CardTitle>Operator Cockpit</CardTitle>
          <CardDescription>{cockpit.headline}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <p className="text-sm text-muted-foreground">{cockpit.summary}</p>
          <div className="grid gap-3 md:grid-cols-3">
            {cockpit.tiles.map(tile => (
              <div key={tile.label} className="rounded-lg border p-4">
                <div className="text-sm text-muted-foreground">{tile.label}</div>
                <div className={`mt-1 text-2xl font-bold ${getTileColor(tile.tone)}`}>
                  {tile.value}
                </div>
                <div className="mt-1 text-xs text-muted-foreground">{tile.detail}</div>
              </div>
            ))}
          </div>
          <div className="space-y-2">
            <div className="text-sm font-medium">Next safe actions</div>
            {cockpit.priorityActions.map((action, index) => (
              <div
                key={`${action.action}-${action.serviceId ?? index}`}
                className={`flex flex-col gap-3 rounded-lg border p-3 sm:flex-row sm:items-center sm:justify-between ${getActionColor(action.severity)}`}
              >
                <div>
                  <div className="font-medium">{action.action}</div>
                  <div className="text-sm opacity-80">{action.detail}</div>
                </div>
                {action.serviceId && (
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => restartService(action.serviceId!)}
                    disabled={pendingRestart === action.serviceId}
                  >
                    {pendingRestart === action.serviceId ? (
                      <Loader2 className="h-4 w-4 animate-spin" />
                    ) : (
                      'Restart'
                    )}
                  </Button>
                )}
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <div className="flex gap-2 border-b">
        {[
          { id: 'overview', label: 'Overview', icon: Activity },
          { id: 'inventory', label: 'VM Inventory', icon: ServerCog },
          { id: 'valkey', label: 'Valkey Inspector', icon: Database },
        ].map(({ id, label, icon: Icon }) => (
          <button
            key={id}
            onClick={() => setActiveTab(id as typeof activeTab)}
            className={`flex items-center gap-2 px-4 py-2 border-b-2 transition-colors ${
              activeTab === id
                ? 'border-emerald-600 text-emerald-700'
                : 'border-transparent hover:border-gray-300'
            }`}
          >
            <Icon className="h-4 w-4" />
            {label}
          </button>
        ))}
      </div>

      {activeTab === 'overview' && (
        <>
          <Card>
            <CardHeader>
              <CardTitle>Ops Links</CardTitle>
              <CardDescription>
                Direct entry points for internal monitoring and health review.
              </CardDescription>
            </CardHeader>
            <CardContent className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
              {OPS_LINKS.map(link => (
                <a
                  key={link.label}
                  href={link.href}
                  target="_blank"
                  rel="noreferrer"
                  className="flex items-center justify-between rounded-lg border px-4 py-3 text-sm hover:bg-accent"
                >
                  <span className="font-medium">{link.label}</span>
                  <ExternalLink className="h-4 w-4 text-muted-foreground" />
                </a>
              ))}
            </CardContent>
          </Card>

          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            {data?.services.map(svc => (
              <Card key={svc.id}>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">{svc.name}</CardTitle>
                  <Activity
                    className={`h-4 w-4 ${svc.status === 'healthy' ? 'text-muted-foreground' : 'text-red-500 animate-pulse'}`}
                  />
                </CardHeader>
                <CardContent>
                  <div className="mb-2 flex items-center justify-between">
                    <Badge variant="outline" className={getStatusColor(svc.status)}>
                      {svc.status}
                    </Badge>
                    <div className={`text-sm font-mono font-bold ${getLatencyColor(svc.latency)}`}>
                      {svc.latency}ms
                    </div>
                  </div>

                  <div className="mt-3 space-y-1">
                    <div className="flex justify-between text-xs">
                      <span className="text-muted-foreground">Group</span>
                      <span className="font-medium">{svc.group}</span>
                    </div>
                    <div className="break-all text-xs font-mono text-muted-foreground">
                      {svc.target}
                    </div>
                    <div className="flex justify-between text-xs">
                      <span className="text-muted-foreground">Uptime (30d)</span>
                      <span className="font-medium">99.9%</span>
                    </div>
                    <Progress value={svc.status === 'down' ? 0 : 99} className="h-1" />
                  </div>

                  {svc.message && (
                    <div className="mt-3 rounded bg-muted p-2 text-xs font-mono text-destructive">
                      {svc.message}
                    </div>
                  )}

                  <div className="mt-3 flex justify-between text-xs text-muted-foreground">
                    <span>v{svc.version || '?'}</span>
                    <span>{new Date(svc.lastChecked).toLocaleTimeString()}</span>
                  </div>
                </CardContent>
              </Card>
            ))}

            {!data &&
              loading &&
              Array.from({ length: 5 }).map((_, i) => (
                <Card key={i}>
                  <CardHeader>
                    <Skeleton className="h-4 w-[150px]" />
                  </CardHeader>
                  <CardContent>
                    <Skeleton className="h-[100px] w-full" />
                  </CardContent>
                </Card>
              ))}
          </div>
        </>
      )}

      {activeTab === 'inventory' && (
        <>
          <div className="grid gap-4 md:grid-cols-4">
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">
                  Managed Services
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold">{inventory?.counts.services ?? 0}</div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">Healthy</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold text-green-600">
                  {inventory?.counts.healthy ?? 0}
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">Down</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold text-red-600">{inventory?.counts.down ?? 0}</div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">
                  Host Tools
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold">{inventory?.counts.hostTools ?? 0}</div>
              </CardContent>
            </Card>
          </div>

          <Card>
            <CardHeader>
              <CardTitle>Service Inventory</CardTitle>
              <CardDescription>
                Live Docker-managed stack reachable from the admin container.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Service</TableHead>
                    <TableHead>Group</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Exposure</TableHead>
                    <TableHead>Port</TableHead>
                    <TableHead>Target</TableHead>
                    <TableHead>Action</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {inventory?.services.map(service => (
                    <TableRow key={service.id}>
                      <TableCell>
                        <div className="font-medium">{service.name}</div>
                        <div className="text-xs text-muted-foreground">{service.description}</div>
                      </TableCell>
                      <TableCell>{service.group}</TableCell>
                      <TableCell>
                        <Badge variant="outline" className={getStatusColor(service.status)}>
                          {service.status}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Badge variant="secondary">{service.exposure}</Badge>
                      </TableCell>
                      <TableCell>{service.port ?? 'n/a'}</TableCell>
                      <TableCell className="max-w-[280px] break-all font-mono text-xs">
                        {service.target}
                      </TableCell>
                      <TableCell>
                        {service.restartable ? (
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => restartService(service.id)}
                            disabled={pendingRestart === service.id}
                          >
                            {pendingRestart === service.id ? (
                              <Loader2 className="h-4 w-4 animate-spin" />
                            ) : (
                              'Restart'
                            )}
                          </Button>
                        ) : (
                          <span className="text-xs text-muted-foreground">n/a</span>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>VM Tooling</CardTitle>
              <CardDescription>
                Host-level tools and mounted config that support the stack.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Tool</TableHead>
                    <TableHead>Group</TableHead>
                    <TableHead>Management</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Description</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {inventory?.hostTools.map(tool => (
                    <TableRow key={tool.id}>
                      <TableCell className="font-medium">{tool.name}</TableCell>
                      <TableCell>{tool.group}</TableCell>
                      <TableCell>{tool.management}</TableCell>
                      <TableCell>
                        <Badge variant={tool.status === 'managed' ? 'default' : 'secondary'}>
                          {tool.status}
                        </Badge>
                      </TableCell>
                      <TableCell>{tool.description}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </>
      )}

      {activeTab === 'valkey' && (
        <>
          <div className="grid gap-4 md:grid-cols-4">
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">Ping</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold">{valkey?.summary.ping ?? '--'}</div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">DB Size</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold">{valkey?.summary.dbsize ?? 0}</div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">
                  Used Memory
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold">{valkey?.summary.usedMemoryHuman ?? '--'}</div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">
                  Peak Memory
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold">
                  {valkey?.summary.usedMemoryPeakHuman ?? '--'}
                </div>
              </CardContent>
            </Card>
          </div>

          <Card>
            <CardHeader>
              <CardTitle>Key Explorer</CardTitle>
              <CardDescription>
                Read-only Valkey inspection for keys, TTLs, and small previews.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex flex-col gap-3 md:flex-row">
                <div className="flex-1">
                  <Input
                    value={valkeyPattern}
                    onChange={event => setValkeyPattern(event.target.value)}
                    placeholder="Pattern, e.g. extraction:*"
                  />
                </div>
                <div className="w-full md:w-28">
                  <Input
                    value={valkeyLimit}
                    onChange={event => setValkeyLimit(event.target.value)}
                    placeholder="25"
                  />
                </div>
                <Button onClick={() => fetchValkey()}>
                  <Search className="mr-2 h-4 w-4" />
                  Inspect
                </Button>
                <Button
                  variant="destructive"
                  onClick={() => deleteValkeyPattern()}
                  disabled={pendingDelete === `pattern:${valkeyPattern}`}
                >
                  {pendingDelete === `pattern:${valkeyPattern}` ? (
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  ) : null}
                  Delete Pattern
                </Button>
              </div>

              <div className="grid gap-4 md:grid-cols-3">
                <div className="rounded-lg border p-4">
                  <div className="mb-1 text-sm text-muted-foreground">Version</div>
                  <div className="font-semibold">{valkey?.summary.version ?? '--'}</div>
                </div>
                <div className="rounded-lg border p-4">
                  <div className="mb-1 text-sm text-muted-foreground">Pattern</div>
                  <div className="font-mono text-sm">{valkey?.pattern ?? '*'}</div>
                </div>
                <div className="rounded-lg border p-4">
                  <div className="mb-1 text-sm text-muted-foreground">Matched</div>
                  <div className="font-semibold">{valkey?.summary.matchedKeys ?? 0}</div>
                </div>
              </div>

              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Key</TableHead>
                    <TableHead>Type</TableHead>
                    <TableHead>TTL</TableHead>
                    <TableHead>Size</TableHead>
                    <TableHead>Preview</TableHead>
                    <TableHead>Action</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {valkeyLoading && (
                    <TableRow>
                      <TableCell colSpan={6}>
                        <div className="flex items-center gap-2 text-sm text-muted-foreground">
                          <RefreshCw className="h-4 w-4 animate-spin" />
                          Loading Valkey state...
                        </div>
                      </TableCell>
                    </TableRow>
                  )}
                  {!valkeyLoading &&
                    valkey?.keys.map(item => (
                      <TableRow key={item.key}>
                        <TableCell className="max-w-[320px] break-all font-mono text-xs">
                          {item.key}
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline">{item.type}</Badge>
                        </TableCell>
                        <TableCell>
                          {item.ttlSeconds < 0 ? 'persistent' : `${item.ttlSeconds}s`}
                        </TableCell>
                        <TableCell>{item.size ?? 'n/a'}</TableCell>
                        <TableCell className="max-w-[360px] break-all font-mono text-xs">
                          {item.preview ?? 'No preview'}
                        </TableCell>
                        <TableCell>
                          <Button
                            size="sm"
                            variant="destructive"
                            onClick={() => deleteValkeyKey(item.key)}
                            disabled={pendingDelete === item.key}
                          >
                            {pendingDelete === item.key ? (
                              <Loader2 className="h-4 w-4 animate-spin" />
                            ) : (
                              'Delete'
                            )}
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </>
      )}

      <Card>
        <CardHeader>
          <CardTitle>Infrastructure Dependencies</CardTitle>
          <CardDescription>Status of external cloud providers and databases.</CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Dependency</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Region</TableHead>
                <TableHead>Status</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              <TableRow>
                <TableCell className="font-medium">Azure Cosmos DB</TableCell>
                <TableCell>Database</TableCell>
                <TableCell>West US 2</TableCell>
                <TableCell>
                  <Badge variant="outline" className="bg-green-500/10 text-green-500">
                    Operational
                  </Badge>
                </TableCell>
              </TableRow>
              <TableRow>
                <TableCell className="font-medium">Azure OpenAI</TableCell>
                <TableCell>AI Model</TableCell>
                <TableCell>Sweden Central</TableCell>
                <TableCell>
                  <Badge variant="outline" className="bg-green-500/10 text-green-500">
                    Operational
                  </Badge>
                </TableCell>
              </TableRow>
              <TableRow>
                <TableCell className="font-medium">Azure Blob Storage</TableCell>
                <TableCell>Storage</TableCell>
                <TableCell>Local Emulator</TableCell>
                <TableCell>
                  <Badge variant="outline" className="bg-green-500/10 text-green-500">
                    Operational
                  </Badge>
                </TableCell>
              </TableRow>
              <TableRow>
                <TableCell className="font-medium">VM Disk + Runtime</TableCell>
                <TableCell>Host</TableCell>
                <TableCell>Azure VM</TableCell>
                <TableCell>
                  <Badge variant="outline" className="bg-green-500/10 text-green-500">
                    Operational
                  </Badge>
                </TableCell>
              </TableRow>
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Internal Stack Coverage</CardTitle>
          <CardDescription>What this admin ops surface covers today.</CardDescription>
        </CardHeader>
        <CardContent className="grid gap-3 md:grid-cols-3">
          <div className="rounded-lg border p-4">
            <div className="mb-2 flex items-center gap-2 font-medium">
              <Activity className="h-4 w-4" />
              Health Review
            </div>
            <p className="text-sm text-muted-foreground">
              Live status for dashboards, core services, observability, ingress, and shared
              infrastructure.
            </p>
          </div>
          <div className="rounded-lg border p-4">
            <div className="mb-2 flex items-center gap-2 font-medium">
              <Database className="h-4 w-4" />
              Valkey Visibility
            </div>
            <p className="text-sm text-muted-foreground">
              Read-only key inspection with type, TTL, size, and preview for current internal data.
            </p>
          </div>
          <div className="rounded-lg border p-4">
            <div className="mb-2 flex items-center gap-2 font-medium">
              <HardDrive className="h-4 w-4" />
              VM Tooling
            </div>
            <p className="text-sm text-muted-foreground">
              Inventory of Docker-managed services plus host tools used to run and operate the VM.
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
