import { getSystemCounts, getEnvHealth } from "@/lib/db/admin-queries"
import { getMaintenanceMode } from "@/lib/settings"
import { aiProviderStatus } from "@/lib/ai/provider"
import { MaintenanceToggle } from "@/components/admin/maintenance-toggle"
import { AiProviderToggle } from "@/components/admin/ai-provider-toggle"
import { formatDate } from "@/lib/utils"
import { Settings, Database, Table2 } from "lucide-react"

export const dynamic = "force-dynamic"

function humanize(name: string): string {
  return name
    .replace(/_/g, " ")
    .replace(/\b\w/g, (c) => c.toUpperCase())
}

export default async function AdminSystemPage() {
  const [{ counts, cronLastRun }, env, maintenance, aiProvider] = await Promise.all([
    getSystemCounts(),
    Promise.resolve(getEnvHealth()),
    getMaintenanceMode(),
    aiProviderStatus(),
  ])

  return (
    <div className="min-h-full">
      {/* Heading */}
      <div className="mb-6">
        <h1 className="text-xl font-bold text-white">System Health</h1>
        <p className="text-sm text-white/40 mt-0.5">
          Configuration, database, and table statistics
        </p>
      </div>

      {/* Maintenance mode control */}
      <div className="mb-5">
        <MaintenanceToggle
          initialEnabled={maintenance.enabled}
          initialMessage={maintenance.message ?? ""}
        />
      </div>

      {/* AI provider selection */}
      <div className="mb-5">
        <AiProviderToggle
          selected={aiProvider.selected}
          effective={aiProvider.effective}
          openaiConfigured={aiProvider.openaiConfigured}
          anthropicConfigured={aiProvider.anthropicConfigured}
          openaiModel={aiProvider.openaiModel}
          anthropicModel={aiProvider.anthropicModel}
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-5 mb-5">
        {/* ── Environment configuration ───────────────────────────────── */}
        <div className="rounded-2xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
          <div className="flex items-center gap-2 border-b border-white/[0.06] px-5 py-4">
            <Settings className="h-4 w-4 text-rose-400 shrink-0" />
            <h2 className="text-sm font-semibold text-white">Environment configuration</h2>
          </div>
          <div className="divide-y divide-white/[0.04]">
            {env.map(({ key, present }) => (
              <div
                key={key}
                className="flex items-center justify-between gap-3 px-5 py-3"
              >
                <span className="font-mono text-xs text-white/60 truncate">{key}</span>
                <span className="flex shrink-0 items-center gap-2">
                  <span
                    className={`h-2 w-2 rounded-full ${
                      present ? "bg-emerald-400" : "bg-amber-400"
                    }`}
                  />
                  <span
                    className={`text-xs font-medium ${
                      present ? "text-emerald-400" : "text-amber-400"
                    }`}
                  >
                    {present ? "Configured" : "Missing"}
                  </span>
                </span>
              </div>
            ))}
          </div>
        </div>

        {/* ── Database ────────────────────────────────────────────────── */}
        <div className="rounded-2xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
          <div className="flex items-center gap-2 border-b border-white/[0.06] px-5 py-4">
            <Database className="h-4 w-4 text-rose-400 shrink-0" />
            <h2 className="text-sm font-semibold text-white">Database</h2>
          </div>
          <div className="divide-y divide-white/[0.04]">
            <div className="flex items-center justify-between gap-3 px-5 py-3">
              <span className="text-sm text-white/60">Connection</span>
              <span className="flex shrink-0 items-center gap-2">
                <span className="h-2 w-2 rounded-full bg-emerald-400" />
                <span className="text-xs font-medium text-emerald-400">Connected</span>
              </span>
            </div>
            <div className="flex items-center justify-between gap-3 px-5 py-3">
              <span className="text-sm text-white/60">Cron last run</span>
              <span className="shrink-0 text-xs text-white/40">
                {cronLastRun ? formatDate(cronLastRun) : "Never run"}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* ── Table row counts ──────────────────────────────────────────── */}
      <div className="rounded-2xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
        <div className="flex items-center gap-2 border-b border-white/[0.06] px-5 py-4">
          <Table2 className="h-4 w-4 text-rose-400 shrink-0" />
          <h2 className="text-sm font-semibold text-white">Table row counts</h2>
        </div>
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-px bg-white/[0.04]">
          {Object.entries(counts).map(([name, value]) => (
            <div key={name} className="bg-[#16161f] px-5 py-4">
              <p className="text-xs font-medium uppercase tracking-wider text-white/40">
                {humanize(name)}
              </p>
              <p className="mt-1.5 text-2xl font-bold tabular-nums text-white">
                {value.toLocaleString()}
              </p>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
