import React from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/common/card";
import { Badge } from "@/components/common/badge";
import { Server, Database, Cpu, HardDrive, Activity, Zap } from "lucide-react";
import { fetchServer } from "@/lib/api";
import SystemStatusCard from "@/components/admin/SystemStatusCard";
import { MotionWrapper } from "@/components/common/motion-wrapper";

export const dynamic = 'force-dynamic';

interface SystemStatus {
  uptimeSeconds: number;
  memory: {
    rss: number;
    heapTotal: number;
    heapUsed: number;
    external: number;
    arrayBuffers: number;
  };
  versions: Record<string, string>;
  counts: {
    vendors: number;
    orders: number;
    products: number;
    chats: number;
  };
}

export default async function AdminStatusPage() {
  let systemStatus: SystemStatus | null = null;
  let error: string | null = null;

  try {
    systemStatus = await fetchServer<SystemStatus>("/admin/system-status");
  } catch (err) {
    console.error("Failed to fetch system status:", err);
    error = "Failed to load system status";
  }

  if (error) {
    return (
      <div className="space-y-8 p-1">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">System Status</h1>
          <p className="text-muted-foreground mt-2">Monitor system health and real-time performance metrics</p>
        </div>
        <Card className="border-destructive/50 bg-destructive/10">
          <CardContent className="pt-6">
            <div className="flex items-center gap-3 text-destructive">
              <Activity className="h-5 w-5" />
              <p className="font-medium">{error}</p>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  const formatUptime = (seconds: number) => {
    const days = Math.floor(seconds / 86400);
    const hours = Math.floor((seconds % 86400) / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    return `${days}d ${hours}h ${minutes}m`;
  };

  const formatBytes = (bytes: number) => {
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    if (bytes === 0) return '0 Bytes';
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
  };

  const memoryUsagePercent = systemStatus ?
    Math.round((systemStatus.memory.heapUsed / systemStatus.memory.heapTotal) * 100) : 0;

  return (
    <div className="space-y-8 p-1">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">
          System Status
        </h1>
        <p className="text-muted-foreground mt-2 text-lg">
          Monitor system health and real-time performance metrics
        </p>
      </div>

      <MotionWrapper>
        <div className="space-y-8">
          <SystemStatusCard />

          <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
            {/* Server Status */}
            <Card className="bg-background/50 backdrop-blur-sm border-border/40 shadow-sm hover:shadow-md transition-all duration-300">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">Server Uptime</CardTitle>
                <div className="p-2 rounded-lg bg-green-500/10">
                  <Server className="h-4 w-4 text-green-500" />
                </div>
              </CardHeader>
              <CardContent>
                <div className="flex items-center space-x-2">
                  <span className="text-2xl font-bold">
                    {systemStatus ? formatUptime(systemStatus.uptimeSeconds) : 'N/A'}
                  </span>
                </div>
                <div className="flex items-center mt-2 space-x-2">
                  <Badge variant="outline" className="bg-green-500/10 text-green-500 border-green-500/20">
                    Online
                  </Badge>
                  <span className="text-xs text-muted-foreground">
                    Checked: {new Date().toLocaleTimeString()}
                  </span>
                </div>
              </CardContent>
            </Card>

            {/* Database Status */}
            <Card className="bg-background/50 backdrop-blur-sm border-border/40 shadow-sm hover:shadow-md transition-all duration-300">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">Database Health</CardTitle>
                <div className="p-2 rounded-lg bg-blue-500/10">
                  <Database className="h-4 w-4 text-blue-500" />
                </div>
              </CardHeader>
              <CardContent>
                <div className="flex items-center space-x-2">
                  <span className="text-2xl font-bold">
                    {systemStatus ? `${(systemStatus.counts.vendors + systemStatus.counts.orders + systemStatus.counts.products).toLocaleString()}` : '0'}
                  </span>
                  <span className="text-sm text-muted-foreground self-end mb-1">records</span>
                </div>
                <div className="flex items-center mt-2 space-x-2">
                  <Badge variant="outline" className="bg-blue-500/10 text-blue-500 border-blue-500/20">
                    Connected
                  </Badge>
                  <span className="text-xs text-muted-foreground">
                    4 active collections
                  </span>
                </div>
              </CardContent>
            </Card>

            {/* Memory Usage */}
            <Card className="bg-background/50 backdrop-blur-sm border-border/40 shadow-sm hover:shadow-md transition-all duration-300">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">Memory Usage</CardTitle>
                <div className="p-2 rounded-lg bg-purple-500/10">
                  <HardDrive className="h-4 w-4 text-purple-500" />
                </div>
              </CardHeader>
              <CardContent>
                <div className="flex items-center space-x-2">
                  <span className="text-2xl font-bold">
                    {systemStatus ? formatBytes(systemStatus.memory.heapUsed) : 'N/A'}
                  </span>
                  <span className="text-sm text-muted-foreground self-end mb-1">used</span>
                </div>
                <div className="flex items-center mt-2 space-x-2">
                  <Badge variant="outline" className={`
                    ${memoryUsagePercent > 80 ? 'bg-red-500/10 text-red-500 border-red-500/20' :
                      memoryUsagePercent > 60 ? 'bg-yellow-500/10 text-yellow-500 border-yellow-500/20' :
                        'bg-purple-500/10 text-purple-500 border-purple-500/20'}
                  `}>
                    {memoryUsagePercent}% Load
                  </Badge>
                  <span className="text-xs text-muted-foreground">
                    Total: {systemStatus ? formatBytes(systemStatus.memory.heapTotal) : 'N/A'}
                  </span>
                </div>
              </CardContent>
            </Card>

            {/* Platform Stats */}
            <Card className="bg-background/50 backdrop-blur-sm border-border/40 shadow-sm hover:shadow-md transition-all duration-300">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">Platform Activity</CardTitle>
                <div className="p-2 rounded-lg bg-orange-500/10">
                  <Activity className="h-4 w-4 text-orange-500" />
                </div>
              </CardHeader>
              <CardContent>
                <div className="flex items-center space-x-2">
                  <span className="text-2xl font-bold">
                    {systemStatus ? systemStatus.counts.vendors : '0'}
                  </span>
                  <span className="text-sm text-muted-foreground self-end mb-1">Active Vendors</span>
                </div>
                <div className="flex items-center mt-2 space-x-2">
                  <Badge variant="outline" className="bg-orange-500/10 text-orange-500 border-orange-500/20">
                    Live
                  </Badge>
                  <span className="text-xs text-muted-foreground">
                    {systemStatus ? `${systemStatus.counts.orders} orders` : '0 orders'}
                  </span>
                </div>
              </CardContent>
            </Card>

            {/* Runtime Info */}
            <Card className="bg-background/50 backdrop-blur-sm border-border/40 shadow-sm hover:shadow-md transition-all duration-300 md:col-span-2 lg:col-span-2">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">Runtime Environment</CardTitle>
                <div className="p-2 rounded-lg bg-zinc-500/10">
                  <Cpu className="h-4 w-4 text-zinc-500" />
                </div>
              </CardHeader>
              <CardContent>
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                  <div className="flex items-center gap-4">
                    <div>
                      <p className="text-2xl font-bold">Node.js</p>
                      <p className="text-xs text-muted-foreground mt-1">Runtime</p>
                    </div>
                    <Badge variant="secondary" className="text-sm h-7">
                      {systemStatus ? `v${systemStatus.versions.node}` : 'N/A'}
                    </Badge>
                  </div>

                  <div className="h-8 w-px bg-border/50 hidden sm:block" />

                  <div className="flex items-center gap-4">
                    <div>
                      <p className="text-2xl font-bold">V8</p>
                      <p className="text-xs text-muted-foreground mt-1">Engine</p>
                    </div>
                    <Badge variant="secondary" className="text-sm h-7">
                      {systemStatus ? systemStatus.versions.v8 : 'N/A'}
                    </Badge>
                  </div>

                  <div className="h-8 w-px bg-border/50 hidden sm:block" />

                  <div className="flex items-center gap-2 text-sm text-muted-foreground bg-muted/30 px-3 py-1.5 rounded-md">
                    <Zap className="h-3.5 w-3.5 text-yellow-500" />
                    <span>Performance Optimized</span>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </MotionWrapper>
    </div>
  );
}


