"use client";

import { useQuery } from "@tanstack/react-query";
import { Building2, Gauge, MapPin, Stethoscope, UserRound } from "lucide-react";
import Link from "next/link";
import { useAuth } from "@/components/auth";
import { apiGet } from "@/lib/api";

type DashboardData = {
  customers: number;
  locations: number;
  contacts: number;
  devices: number;
  equipment: number;
  validations: number;
};

const cards = [
  { label: "Kunden", key: "customers", href: "/customers", icon: Building2 },
  { label: "Standorte", key: "locations", href: "/locations", icon: MapPin },
  { label: "Ansprechpartner", key: "contacts", href: "/contacts", icon: UserRound },
  { label: "Geraete", key: "devices", href: "/devices", icon: Stethoscope },
  { label: "Pruefmittel", key: "equipment", href: "/equipment", icon: Gauge }
] as const;

export default function DashboardPage() {
  const { token } = useAuth();
  const query = useQuery({
    queryKey: ["dashboard", token],
    queryFn: () => apiGet<DashboardData>("/dashboard", token ?? ""),
    enabled: Boolean(token)
  });

  return (
    <div className="space-y-8">
      <header>
        <h1 className="text-3xl font-semibold text-text">Dashboard</h1>
        <p className="mt-2 text-text-light">Aktuelle Stammdaten aus PostgreSQL.</p>
      </header>
      <section className="grid gap-4 sm:grid-cols-2 xl:grid-cols-5">
        {cards.map((item) => {
          const Icon = item.icon;
          return (
            <Link key={item.key} href={item.href} className="rounded-lg border border-border bg-surface p-6 shadow-soft transition hover:-translate-y-0.5 hover:border-primary/40">
              <div className="flex items-center justify-between">
                <p className="text-sm text-text-light">{item.label}</p>
                <Icon className="h-5 w-5 text-primary" />
              </div>
              <p className="mt-6 text-4xl font-semibold text-text">{query.data?.[item.key] ?? 0}</p>
            </Link>
          );
        })}
      </section>
      <section className="rounded-lg border border-border bg-surface p-6 shadow-soft">
        <h2 className="text-xl font-semibold">Stammdaten</h2>
        <p className="mt-2 text-sm leading-6 text-text-light">Kunden, Standorte, Ansprechpartner, Geraete und Pruefmittel koennen produktiv angelegt, bearbeitet, gesucht und geloescht werden.</p>
      </section>
    </div>
  );
}
