import { MetricPill } from "@/components/dashboard/shared/MetricPill";
import { 
  ShoppingBag, 
  Users, 
  Euro, 
  TrendingUp, 
  Package, 
  AlertTriangle,
  UserCheck,
  Plus,
  BarChart3,
  UserCog,
  LayoutDashboard
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { OrderRepository } from "@/lib/db/repositories/order.repository";
import { CustomerRepository } from "@/lib/db/repositories/customer.repository";
import { CatalogRepository } from "@/lib/db/repositories/catalog.repository";
import { UserRepository } from "@/lib/db/repositories/user.repository";
import { formatCurrency } from "@/lib/format";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Suspense } from "react";
import { ChartsWrapper } from "./ChartsWrapper";
import { DashboardSkeleton } from "@/components/dashboard/shared/DashboardSkeleton";

export default async function DashboardPage() {
  const orderRepo = new OrderRepository();
  const customerRepo = new CustomerRepository();
  const catalogRepo = new CatalogRepository();
  const userRepo = new UserRepository();

  const [
    revenue, 
    ordersCount, 
    customerCount, 
    lowStockCount, 
    onlineCount
  ] = await Promise.all([
    orderRepo.getTotalRevenue().catch(() => 0),
    orderRepo.getTotalOrdersCount().catch(() => 0),
    customerRepo.getTotalCustomersCount().catch(() => 0),
    catalogRepo.getLowStockCount().catch(() => 0),
    userRepo.getOnlineStaffCount().catch(() => 0),
  ]);

  return (
    <div className="space-y-8">
      {/* Page Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="space-y-1">
          <h1 className="text-2xl font-bold tracking-tight flex items-center gap-2">
            <LayoutDashboard className="size-6 text-primary" aria-hidden="true" />
            Dashboard Overview
          </h1>
          <p className="text-muted-foreground text-sm">Willkommen zurück. Hier ist der aktuelle Status Ihres Shops.</p>
        </div>
        <div className="flex items-center gap-3">
          <MetricPill 
            icon={<UserCheck className="size-3.5 shrink-0" aria-hidden="true" />}
            label="Staff Online" 
            value={onlineCount} 
            variant={onlineCount > 0 ? "success" : "default"} 
            tooltip={`${onlineCount} Mitarbeiter sind gerade aktiv`}
          />
          <Link href="/dashboard/products/create">
            <Button size="sm" className="font-bold uppercase text-xs tracking-wide shadow-md shadow-primary/10">
              <Plus className="size-3.5 mr-1.5" aria-hidden="true" /> Produkt
            </Button>
          </Link>
        </div>
      </div>

      {/* Main Metrics Grid */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card className="shadow-sm border-border/40">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-xs font-bold uppercase tracking-normal text-muted-foreground">Gesamtumsatz</CardTitle>
            <div className="size-8 rounded-full bg-emerald-500/10 flex items-center justify-center">
              <Euro className="size-4 text-emerald-600" aria-hidden="true" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold tracking-tight">{formatCurrency(revenue)}</div>
            <div className="flex items-center gap-1 mt-1 text-xs font-semibold text-emerald-600 bg-emerald-500/5 w-fit px-1.5 py-0.5 rounded">
              <TrendingUp className="size-3" aria-hidden="true" /> +12.5%
            </div>
          </CardContent>
        </Card>
        
        <Card className="shadow-sm border-border/40">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-xs font-bold uppercase tracking-normal text-muted-foreground">Bestellungen</CardTitle>
            <div className="size-8 rounded-full bg-blue-500/10 flex items-center justify-center">
              <ShoppingBag className="size-4 text-blue-600" aria-hidden="true" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold tracking-tight">{ordersCount}</div>
            <p className="text-xs text-muted-foreground font-medium mt-1 uppercase">Lebenszeit Gesamt</p>
          </CardContent>
        </Card>

        <Card className="shadow-sm border-border/40">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-xs font-bold uppercase tracking-normal text-muted-foreground">Kunden</CardTitle>
            <div className="size-8 rounded-full bg-purple-500/10 flex items-center justify-center">
              <Users className="size-4 text-purple-600" aria-hidden="true" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold tracking-tight">{customerCount}</div>
            <p className="text-xs text-muted-foreground font-medium mt-1 uppercase">Aktive Konten</p>
          </CardContent>
        </Card>

        <Card className="shadow-sm border-border/40">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-xs font-bold uppercase tracking-normal text-muted-foreground">Lager-Warnung</CardTitle>
            <div className={cn(
              "size-8 rounded-full flex items-center justify-center",
              lowStockCount > 0 ? "bg-amber-500/10" : "bg-muted"
            )}>
              <AlertTriangle className={cn("size-4", lowStockCount > 0 ? "text-amber-600" : "text-muted-foreground")} aria-hidden="true" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold tracking-tight">{lowStockCount} Items</div>
            <p className={cn(
              "text-xs font-bold mt-1 uppercase",
              lowStockCount > 0 ? "text-amber-600" : "text-muted-foreground"
            )}>
              Bestand unter 10 Einheiten
            </p>
          </CardContent>
        </Card>
      </div>

      {/* BI Section with Charts & Recent Data */}
      <Suspense fallback={<DashboardSkeleton />}>
        <ChartsWrapper />
      </Suspense>
    </div>
  );
}

function cn(...inputs: any[]) {
  return inputs.filter(Boolean).join(" ");
}
