import React, { Suspense } from "react";
import AnalyticsClient from "./AnalyticsClient";
import { OrderRepository } from "@/lib/db/repositories/order.repository";
import { CatalogRepository } from "@/lib/db/repositories/catalog.repository";
import { CustomerRepository } from "@/lib/db/repositories/customer.repository";
import { MetricPill } from "@/components/dashboard/shared/MetricPill";
import { Euro, ShoppingCart, Activity, Package, Users } from "lucide-react";
import { formatCurrency } from "@/lib/format";

function buildSalesData(
  rawData: Array<{ name: string; total: string | number }>,
) {
  const today = new Date();
  const last7Days = Array.from({ length: 7 }, (_, index) => {
    const day = new Date(today);
    day.setDate(today.getDate() - (6 - index));
    const isoDate = day.toISOString().slice(0, 10);
    return {
      isoDate,
      label: day.toLocaleDateString("de-DE", { weekday: "short" }),
    };
  });

  const revenueMap = new Map(
    rawData.map((item) => [item.name, Number(item.total || 0)]),
  );

  return last7Days.map((day) => ({
    name: day.label,
    total: revenueMap.get(day.isoDate) ?? 0,
  }));
}

export default async function AnalyticsPage() {
  const orderRepo = new OrderRepository();
  const catalogRepo = new CatalogRepository();

  const customerRepo = new CustomerRepository();

  const [
    rawSalesData,
    topProducts,
    totalRevenue,
    totalOrders,
    totalCustomers,
    lowStockCount,
    lowStockItems,
    revenueByCategory,
    topCustomers,
  ] = await Promise.all([
    orderRepo.getDailyRevenue(),
    catalogRepo.getTopSellingProducts(5),
    orderRepo.getTotalRevenue(),
    orderRepo.getTotalOrdersCount(),
    customerRepo.getTotalCustomersCount(),
    catalogRepo.getLowStockCount(),
    catalogRepo.getLowStockItems(5),
    orderRepo.getRevenueByCategory(),
    orderRepo.getTopCustomers(5),
  ]);

  const salesData = buildSalesData(rawSalesData);
  const avgOrderValue = totalOrders > 0 ? totalRevenue / totalOrders : 0;

  return (
    <div className="space-y-8">
      <div className="flex flex-col gap-2">
        <h1 className="text-2xl font-bold tracking-tight">
          Business Intelligence
        </h1>
        <p className="text-muted-foreground">
          Analysieren Sie die Performance Ihres Shops mit detaillierten
          Kennzahlen.
        </p>
      </div>

      <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
        <MetricPill
          label="Gesamtumsatz"
          value={formatCurrency(totalRevenue)}
          icon={<Euro className="size-3.5 shrink-0" />}
          variant="default"
        />
        <MetricPill
          label="Bestellungen"
          value={totalOrders}
          icon={<ShoppingCart className="size-3.5 shrink-0" />}
          variant="info"
        />
        <MetricPill
          label="Kunden"
          value={totalCustomers}
          icon={<Users className="size-3.5 shrink-0" />}
          variant="info"
        />
        <MetricPill
          label="Durchschn. Bestellwert"
          value={formatCurrency(avgOrderValue)}
          icon={<Activity className="size-3.5 shrink-0" />}
          variant="success"
        />
        <MetricPill
          label="Low Stock Produkte"
          value={lowStockCount}
          icon={<Package className="size-3.5 shrink-0" />}
          variant="warning"
        />
      </div>

      <Suspense
        fallback={
          <div className="h-96 flex items-center justify-center text-muted-foreground">
            Analysen werden geladen...
          </div>
        }
      >
        <AnalyticsClient
          salesData={salesData}
          topProducts={topProducts}
          lowStockItems={lowStockItems.map((item) => ({
            name: item.name,
            inventory: item.inventory ?? 0,
          }))}
          revenueByCategory={revenueByCategory}
          topCustomers={topCustomers}
        />
      </Suspense>
    </div>
  );
}
