import React from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Package, AlertTriangle } from "lucide-react";
import { fetchServer } from "@/lib/api";
import OrdersTable from "@/components/admin/OrdersTable";

export const dynamic = 'force-dynamic';

interface Order {
  orderId: string | number;
  userId: string;
  total: number;
  createdAt: string;
  status: string;
  items: Array<{
    name: string;
    quantity: number;
  }>;
  vendorUsername?: string;
}

interface SystemStats {
  vendors: number;
  orders: number;
  products: number;
  chats: number;
}


export default async function AdminOrdersPage() {
  let orders: Order[] = [];
  let systemStats: SystemStats | null = null;
  let error: string | null = null;

  try {
    const [ordersData, statsData] = await Promise.all([
      fetchServer<Order[]>("/admin/recent-orders"),
      fetchServer<SystemStats>("/admin/stats")
    ]);
    orders = ordersData;
    systemStats = statsData;
  } catch (err) {
    console.error("Failed to fetch data:", err);
    error = "Failed to load data";
  }

  if (error) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">Recent Orders</h1>
          <p className="text-sm text-muted-foreground mt-1">Monitor and manage platform orders</p>
        </div>
        <Card>
          <CardContent className="pt-6">
            <div className="text-center text-red-500">
              <p>{error}</p>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  
  const acknowledgedOrders = orders.filter(o => o.status === 'acknowledged');
  const paidOrders = orders.filter(o => o.status === 'paid');
  const completedOrders = orders.filter(o => o.status === 'completed');
  const cancelledOrders = orders.filter(o => o.status === 'cancelled');

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">Recent Orders</h1>
        <p className="text-sm text-muted-foreground mt-1">Monitor and manage platform orders</p>
      </div>

      {/* Stats Cards */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Orders</CardTitle>
            <Package className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{systemStats?.orders || 0}</div>
            <p className="text-xs text-muted-foreground">All platform orders</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Acknowledged</CardTitle>
            <AlertTriangle className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{acknowledgedOrders.length}</div>
            <p className="text-xs text-muted-foreground">Vendor accepted</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Paid</CardTitle>
            <Package className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{paidOrders.length}</div>
            <p className="text-xs text-muted-foreground">Payment received</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Completed</CardTitle>
            <Package className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{completedOrders.length}</div>
            <p className="text-xs text-muted-foreground">Successfully delivered</p>
          </CardContent>
        </Card>
      </div>

      {/* Orders Table with Pagination */}
      <OrdersTable orders={orders} />

      {/* Order Analytics */}
      <div className="grid gap-6 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>Order Status Distribution</CardTitle>
            <CardDescription>Breakdown of recent orders by status</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <div className="w-3 h-3 bg-purple-500 rounded-full"></div>
                  <span className="text-sm">Acknowledged</span>
                </div>
                <span className="text-sm font-medium">
                  {orders.length > 0 ? Math.round((acknowledgedOrders.length / orders.length) * 100) : 0}%
                </span>
              </div>
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <div className="w-3 h-3 bg-emerald-500 rounded-full"></div>
                  <span className="text-sm">Paid</span>
                </div>
                <span className="text-sm font-medium">
                  {orders.length > 0 ? Math.round((paidOrders.length / orders.length) * 100) : 0}%
                </span>
              </div>
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <div className="w-3 h-3 bg-green-500 rounded-full"></div>
                  <span className="text-sm">Completed</span>
                </div>
                <span className="text-sm font-medium">
                  {orders.length > 0 ? Math.round((completedOrders.length / orders.length) * 100) : 0}%
                </span>
              </div>
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <div className="w-3 h-3 bg-red-500 rounded-full"></div>
                  <span className="text-sm">Cancelled</span>
                </div>
                <span className="text-sm font-medium">
                  {orders.length > 0 ? Math.round((cancelledOrders.length / orders.length) * 100) : 0}%
                </span>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Order Summary</CardTitle>
            <CardDescription>Recent order activity breakdown</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-sm">Total Recent Orders</span>
                <span className="text-sm font-medium">{orders.length}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm">Acknowledged</span>
                <span className="text-sm font-medium">{acknowledgedOrders.length}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm">Paid</span>
                <span className="text-sm font-medium">{paidOrders.length}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm">Completed</span>
                <span className="text-sm font-medium">{completedOrders.length}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm">Cancelled</span>
                <span className="text-sm font-medium">{cancelledOrders.length}</span>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
