import type { Metadata } from "next";
import Link from "next/link";
import { PageHeader } from "@/components/layout/page-header";
import { RUN_STATUS, runDuration, runTriggerLabel } from "@/components/settings/run-meta";
import { SettingsForm } from "@/components/settings/settings-form";
import { Card } from "@/components/ui/card";
import { cn } from "@/lib/cn";
import { formatDateTime } from "@/lib/format";
import { FREQUENCY_LABELS, nextSlot } from "@/lib/schedule";
import { requireAdmin } from "@/server/auth/session";
import { env } from "@/server/env";
import { listRecentRuns } from "@/server/scheduler/runs";
import { getMonitoringSettings } from "@/server/settings/service";

export const metadata: Metadata = { title: "Monitoring Settings" };

const th = "px-4 py-2.5 text-left text-xs font-medium text-slate-500";
const td = "px-4 py-2.5 align-middle";
const dash = <span className="text-slate-300">—</span>;

function timezoneOptions(current: string): string[] {
  // Some runtimes list only the legacy alias (Asia/Calcutta); make sure the
  // modern name and whatever is currently saved are always selectable.
  return [...new Set([...Intl.supportedValuesOf("timeZone"), "Asia/Kolkata", "UTC", current])].sort();
}

export default async function SettingsPage() {
  await requireAdmin();

  const [settings, runs] = await Promise.all([getMonitoringSettings(), listRecentRuns(10)]);
  const tz = settings.timezone;

  const schedulerNote =
    env.SCHEDULER_MODE === "internal"
      ? `Next scheduled check: ${formatDateTime(nextSlot(settings, new Date()), tz)}`
      : env.SCHEDULER_MODE === "external"
        ? "Scheduled checks are triggered externally through /api/cron/tick."
        : "Scheduled checks are switched off (SCHEDULER_MODE=off).";

  return (
    <>
      <PageHeader title="Monitoring Settings" />

      <Card className="mb-5 p-5">
        <SettingsForm
          initialValues={{
            frequency: settings.frequency,
            checkTime: settings.checkTime,
            timezone: settings.timezone,
            slowThresholdSeconds: String(settings.slowThresholdSeconds),
          }}
          timezones={timezoneOptions(settings.timezone)}
        />
      </Card>

      <Card className="overflow-hidden">
        <div className="flex flex-wrap items-baseline justify-between gap-2 border-b border-slate-200 px-4 py-3">
          <h2 className="text-sm font-semibold text-slate-900">Recent Check Runs</h2>
          <p className="text-xs text-slate-500">
            {FREQUENCY_LABELS[settings.frequency]} · {schedulerNote}
          </p>
        </div>

        {runs.length === 0 ? (
          <p className="px-4 py-10 text-center text-sm text-slate-500">
            No check runs yet. The first scheduled run will appear here.
          </p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[44rem] border-collapse text-sm whitespace-nowrap">
              <thead className="border-b border-slate-200 bg-slate-50">
                <tr>
                  <th scope="col" className={th}>Started</th>
                  <th scope="col" className={th}>Trigger</th>
                  <th scope="col" className={th}>Result</th>
                  <th scope="col" className={`${th} text-right`}>Checked</th>
                  <th scope="col" className={`${th} text-right`}>Working</th>
                  <th scope="col" className={`${th} text-right`}>Slow</th>
                  <th scope="col" className={`${th} text-right`}>Not Working</th>
                  <th scope="col" className={`${th} text-right`}>Disabled</th>
                  <th scope="col" className={`${th} text-right`}>Duration</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {runs.map((run) => (
                  <tr key={run.id}>
                    <td className={`${td} text-xs`}>
                      <Link
                        href={`/settings/runs/${run.id}`}
                        title="Show the apps checked in this run"
                        className="font-medium text-slate-900 underline decoration-slate-300 underline-offset-2 hover:decoration-slate-900"
                      >
                        {formatDateTime(run.startedAt, tz)}
                      </Link>
                    </td>
                    <td className={`${td} text-xs text-slate-600`}>{runTriggerLabel(run)}</td>
                    <td className={cn(td, "text-xs font-medium", RUN_STATUS[run.status].className)}>
                      <span title={run.errorMessage ?? undefined}>{RUN_STATUS[run.status].label}</span>
                      {run.errored ? <span className="font-normal text-red-700"> · {run.errored} errored</span> : null}
                    </td>
                    <td className={`${td} text-right tabular-nums text-slate-700`}>
                      {run.appsChecked ?? dash}
                      {run.appsFound !== null && <span className="text-slate-400"> / {run.appsFound}</span>}
                    </td>
                    <td className={`${td} text-right tabular-nums text-slate-700`}>{run.working ?? dash}</td>
                    <td className={cn(td, "text-right tabular-nums", run.slow ? "font-medium text-amber-700" : "text-slate-700")}>
                      {run.slow ?? dash}
                    </td>
                    <td className={cn(td, "text-right tabular-nums", run.notWorking ? "font-medium text-red-700" : "text-slate-700")}>
                      {run.notWorking ?? dash}
                    </td>
                    <td className={`${td} text-right tabular-nums text-slate-700`}>{run.disabled ?? dash}</td>
                    <td className={`${td} text-right tabular-nums text-xs text-slate-600`}>
                      {runDuration(run.startedAt, run.finishedAt) ?? dash}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </>
  );
}
