import { redirect } from "next/navigation";
import AdminShell from "@/components/admin/AdminShell";
import { requireAdminSession } from "@/lib/admin/auth";
import { getContactInquiries, getRepairInquiries } from "@/lib/admin/store";

function countNew<T extends { status: string }>(items: T[]) {
  return items.filter((item) => item.status === "new").length;
}

export default async function AdminDashboardPage() {
  if (!await requireAdminSession()) redirect("/admin/login");
  const [contacts, repairs] = await Promise.all([getContactInquiries(), getRepairInquiries()]);
  const latest = [...contacts, ...repairs].sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, 6);

  return (
    <AdminShell>
      <div className="admin-page-head">
        <p className="eyebrow">Administration</p>
        <h1>Dashboard</h1>
      </div>
      <div className="admin-kpis">
        <div className="admin-kpi"><span>Kontaktanfragen</span><strong>{countNew(contacts)}</strong><small>neu</small></div>
        <div className="admin-kpi"><span>Reparaturanfragen</span><strong>{countNew(repairs)}</strong><small>neu</small></div>
        <div className="admin-kpi"><span>Website</span><strong>Online</strong><small>OK</small></div>
        <div className="admin-kpi"><span>SMTP</span><strong>Vorbereitet</strong><small>nicht aktiv</small></div>
      </div>
      <section className="admin-card">
        <h2>Letzte Anfragen</h2>
        <table className="admin-table">
          <thead><tr><th>Datum</th><th>Name</th><th>Typ</th><th>Status</th></tr></thead>
          <tbody>
            {latest.map((item) => (
              <tr key={item.id}>
                <td>{new Date(item.createdAt).toLocaleDateString("de-DE")}</td>
                <td>{item.name}</td>
                <td>{"manufacturer" in item ? "Reparatur" : "Kontakt"}</td>
                <td><span className={`status ${item.status}`}>{item.status}</span></td>
              </tr>
            ))}
            {latest.length === 0 && <tr><td colSpan={4}>Noch keine Anfragen vorhanden.</td></tr>}
          </tbody>
        </table>
      </section>
    </AdminShell>
  );
}
