import { redirect } from "next/navigation";
import AdminShell from "@/components/admin/AdminShell";
import { requireAdminSession } from "@/lib/admin/auth";
import { listMediaFiles } from "@/lib/admin/media";
import { getContactInquiries, getRepairInquiries } from "@/lib/admin/store";
import { getContentSummary } from "@/lib/content/service";
import { getSmtpSettings, isSmtpConfigured } from "@/lib/mail/config";
import { appVersion, checkStorage } from "@/lib/runtime/config";

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");
  let healthStatus = "OK";

  try {
    await checkStorage();
  } catch {
    healthStatus = "Fehler";
  }

  const [contacts, repairs, smtpSettings, mediaFiles, contentSummary] = await Promise.all([
    getContactInquiries(),
    getRepairInquiries(),
    getSmtpSettings(),
    listMediaFiles(),
    getContentSummary(),
  ]);
  const latest = [...contacts, ...repairs].sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, 6);
  const contentModified = contentSummary.lastModified ? new Date(contentSummary.lastModified).toLocaleString("de-DE") : "keine Änderung";

  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>{contacts.length}</strong><small>{countNew(contacts)} neu</small></div>
        <div className="admin-kpi"><span>Reparaturanfragen</span><strong>{repairs.length}</strong><small>{countNew(repairs)} neu</small></div>
        <div className="admin-kpi"><span>Medien</span><strong>{mediaFiles.length}</strong><small>im Storage</small></div>
        <div className="admin-kpi"><span>Content</span><strong>{contentSummary.pageCount}</strong><small>{contentModified}</small></div>
        <div className="admin-kpi"><span>SMTP</span><strong>{isSmtpConfigured(smtpSettings) ? "OK" : "Fehlt"}</strong><small>{smtpSettings.lastTestStatus ?? "kein Test"}</small></div>
        <div className="admin-kpi"><span>Version</span><strong>v{appVersion}</strong><small>Website</small></div>
        <div className="admin-kpi"><span>Health</span><strong>{healthStatus}</strong><small>Storage und Runtime</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>
  );
}
