import type { Metadata } from "next";
import type { ReactNode } from "react";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { ArrowLeft, Pencil } from "lucide-react";
import { CheckNowButton } from "@/components/apps/check-now-button";
import { DomainStatusBadge } from "@/components/domains/domain-status-badge";
import { StatusTimeline } from "@/components/apps/status-timeline";
import { ButtonLink } from "@/components/ui/button-link";
import { Card } from "@/components/ui/card";
import { Pagination } from "@/components/ui/pagination";
import { STATUS_STYLES, StatusBadge } from "@/components/ui/status-badge";
import { cn } from "@/lib/cn";
import { formatDaysLeft } from "@/lib/domains/status";
import { formatDate, formatDateTime, formatDuration, formatElapsed, formatPercent, formatResponseTime } from "@/lib/format";
import { STATUS_LABELS, displayStatus, type HealthStatus } from "@/lib/status";
import { canEdit } from "@/lib/auth/roles";
import { requireUser } from "@/server/auth/session";
import { getDomainForUrl } from "@/server/domains/service";
import { HISTORY_PAGE_SIZE, getHealthStats, listHealthChecks, listRecentOutcomes } from "@/server/health/history";
import { getProject } from "@/server/projects/service";
import { getMonitoringSettings } from "@/server/settings/service";

export const metadata: Metadata = { title: "Application Details" };

type AppDetailsPageProps = {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
};

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>;

const HISTORY_FILTERS: Record<string, HealthStatus> = { working: "WORKING", slow: "SLOW", "not-working": "NOT_WORKING" };

function historyHref(id: string, { status, page }: { status: string; page: number }): string {
  const params = new URLSearchParams();
  if (status) params.set("status", status);
  if (page > 1) params.set("page", String(page));
  const query = params.toString();
  return query ? `/apps/${id}?${query}` : `/apps/${id}`;
}

function Detail({ label, children, className }: { label: string; children: ReactNode; className?: string }) {
  return (
    <div className={className}>
      <dt className="text-xs font-medium text-slate-500">{label}</dt>
      <dd className="mt-0.5 text-sm break-words text-slate-900">{children}</dd>
    </div>
  );
}

function Stat({ label, value, hint, emphasis }: { label: string; value: ReactNode; hint?: string; emphasis?: string }) {
  return (
    <div className="rounded-lg border border-slate-200 bg-white px-4 py-3">
      <p className="text-xs font-medium text-slate-500">{label}</p>
      <p className={cn("mt-1 text-xl font-semibold tabular-nums", emphasis ?? "text-slate-900")}>{value}</p>
      {hint && <p className="mt-0.5 text-xs text-slate-500">{hint}</p>}
    </div>
  );
}

export default async function AppDetailsPage({ params, searchParams }: AppDetailsPageProps) {
  const editable = canEdit(await requireUser());

  const { id } = await params;
  const project = await getProject(id);
  if (!project) notFound();

  const query = await searchParams;
  const rawPage = query.page;
  const page = Math.max(1, Number.parseInt((Array.isArray(rawPage) ? rawPage[0] : rawPage) ?? "", 10) || 1);
  const statusKey = (Array.isArray(query.status) ? query.status[0] : query.status) ?? "";
  const historyStatus = HISTORY_FILTERS[statusKey] ?? null;
  const statusParam = historyStatus ? statusKey : "";

  const [{ checks, total, pageCount }, stats, recent, settings, domain] = await Promise.all([
    listHealthChecks(project.id, page, historyStatus),
    getHealthStats(project.id, 30),
    listRecentOutcomes(project.id, 60),
    getMonitoringSettings(),
    getDomainForUrl(project.productionUrl),
  ]);
  if (page > pageCount) redirect(historyHref(project.id, { status: statusParam, page: pageCount }));

  const tz = settings.timezone;
  const when = (date: Date | null) => (date ? formatDateTime(date, tz) : dash);

  const status = displayStatus(project);
  const failing = status === "NOT_WORKING";
  const slow = status === "SLOW";
  const disabled = status === "DISABLED";

  const filterTabs: Array<{ key: string; label: string; count: number | null }> = [
    { key: "", label: "All", count: null },
    { key: "working", label: STATUS_LABELS.WORKING, count: stats.working },
    { key: "slow", label: STATUS_LABELS.SLOW, count: stats.slow },
    { key: "not-working", label: STATUS_LABELS.NOT_WORKING, count: stats.notWorking },
  ];

  return (
    <>
      <Link
        href="/"
        className="mb-3 inline-flex items-center gap-1 text-xs font-medium text-slate-500 hover:text-slate-900"
      >
        <ArrowLeft className="size-3.5" aria-hidden />
        Dashboard
      </Link>

      <div className="mb-5 flex flex-wrap items-center justify-between gap-3">
        <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
          <h1 className="truncate text-base font-semibold text-slate-900">{project.projectName}</h1>
          <StatusBadge status={status} />
        </div>
        {editable && (
          <div className="flex items-center gap-2">
            <CheckNowButton id={project.id} name={project.projectName} disabled={!project.monitoringEnabled} size="md" />
            <ButtonLink href={`/apps/${project.id}/edit`} variant="secondary">
              <Pencil className="size-4" aria-hidden />
              Edit
            </ButtonLink>
          </div>
        )}
      </div>

      {failing && project.failureStartedAt && (
        <div role="status" className="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3">
          <p className="text-sm font-medium text-red-800">
            Not working since {formatDateTime(project.failureStartedAt, tz)}
            <span className="ml-1.5 font-normal text-red-700">({formatElapsed(project.failureStartedAt)})</span>
          </p>
          {project.currentErrorMessage && <p className="mt-0.5 text-sm text-red-700">{project.currentErrorMessage}</p>}
        </div>
      )}

      {slow && (
        <div role="status" className="mb-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3">
          <p className="text-sm font-medium text-amber-800">
            Health API response time too long
            {project.currentResponseTimeMs !== null && (
              <span className="ml-1.5 font-normal text-amber-700">
                — {formatResponseTime(project.currentResponseTimeMs)} on the last check, above the {settings.slowThresholdSeconds} s
                threshold
              </span>
            )}
          </p>
          <p className="mt-0.5 text-sm text-amber-700">
            The API is answering with the expected status, so this does not count as an outage.
          </p>
        </div>
      )}

      <div className="mb-4 grid grid-cols-2 gap-3 lg:grid-cols-4">
        <Stat
          label={`Availability · ${stats.days} days`}
          value={stats.uptimePercent === null ? dash : formatPercent(stats.uptimePercent)}
          hint={stats.total === 0 ? "No checks yet" : `${stats.working + stats.slow} of ${stats.total} checks responded`}
          emphasis={stats.uptimePercent !== null && stats.uptimePercent < 100 ? "text-red-700" : undefined}
        />
        <Stat
          label={`Checks · ${stats.days} days`}
          value={stats.total}
          hint={stats.total === 0 ? undefined : `${stats.working} working · ${stats.slow} slow · ${stats.notWorking} not working`}
        />
        <Stat
          label="Average response"
          value={stats.averageResponseMs === null ? dash : formatDuration(stats.averageResponseMs)}
          hint="Responding checks only"
        />
        <Stat
          label="Slowest response"
          value={stats.slowestResponseMs === null ? dash : formatDuration(stats.slowestResponseMs)}
          hint={`Slow above ${settings.slowThresholdSeconds} s`}
          emphasis={stats.slowestResponseMs !== null && stats.slowestResponseMs > settings.slowThresholdSeconds * 1000 ? "text-amber-700" : undefined}
        />
      </div>

      <div className="mb-5 grid gap-4 lg:grid-cols-2">
        <Card className="p-4">
          <h2 className="mb-3 text-sm font-semibold text-slate-900">
            {disabled ? "Last Known Status" : "Current Status"}
          </h2>
          {disabled && (
            <p className="mb-3 text-xs text-slate-500">
              Monitoring is disabled, so no checks are running. These values are from before it was switched off.
            </p>
          )}
          <dl className="grid grid-cols-2 gap-x-4 gap-y-3">
            <Detail label="Last Checked">{when(project.lastCheckedAt)}</Detail>
            <Detail label="Not Working Since">{when(project.failureStartedAt)}</Detail>
            <Detail label="HTTP Status">{project.currentHttpStatus ?? dash}</Detail>
            <Detail label="Response Time">
              {project.currentResponseTimeMs !== null ? (
                <span className={slow ? "font-medium text-amber-700" : undefined}>{formatResponseTime(project.currentResponseTimeMs)}</span>
              ) : (
                dash
              )}
            </Detail>
            <Detail label={slow ? "Note" : "Error"} className="col-span-2">
              {project.currentErrorMessage ? (
                <span className={slow ? "text-amber-700" : "text-red-700"}>{project.currentErrorMessage}</span>
              ) : (
                dash
              )}
            </Detail>
            <Detail label="Last Successful Check">{when(project.lastSuccessfulCheckAt)}</Detail>
            <Detail label="Last Failed Check">{when(project.lastFailedCheckAt)}</Detail>
            <Detail label="Last Recovered At">{when(project.lastRecoveredAt)}</Detail>
          </dl>
        </Card>

        <Card className="p-4">
          <h2 className="mb-3 text-sm font-semibold text-slate-900">Configuration</h2>
          <dl className="grid grid-cols-2 gap-x-4 gap-y-3">
            <Detail label="Project Code">
              <span className="font-mono text-xs">{project.projectCode}</span>
            </Detail>
            <Detail label="Monitoring">{project.monitoringEnabled ? "Enabled" : "Disabled"}</Detail>
            <Detail label="Production Health API" className="col-span-2">
              <span className="font-mono text-xs break-all">{project.productionUrl}</span>
            </Detail>
            <Detail label="Domain" className="col-span-2">
              {domain ? (
                <span className="flex flex-wrap items-center gap-x-2 gap-y-1">
                  <Link href="/domains" className="hover:underline">
                    {domain.name}
                  </Link>
                  <DomainStatusBadge status={domain.status} />
                  {domain.domain?.hiddenAt && <span className="text-xs text-slate-500">(hidden on the Domains page, not checked)</span>}
                  {domain.expiry && (
                    <span className="text-xs text-slate-500">
                      Expires {formatDate(domain.expiry, tz)}
                      {domain.daysLeft !== null && ` (${formatDaysLeft(domain.daysLeft)})`}
                    </span>
                  )}
                </span>
              ) : (
                <span className="text-xs text-slate-500">No registered domain (IP address or internal host)</span>
              )}
            </Detail>
            <Detail label="Expected HTTP Status">{project.expectedHttpStatus}</Detail>
            <Detail label="Timeout">{project.timeoutSeconds} seconds</Detail>
            {project.description && (
              <Detail label="Description" className="col-span-2">
                <span className="whitespace-pre-line">{project.description}</span>
              </Detail>
            )}
            <Detail label="Created">{formatDateTime(project.createdAt, tz)}</Detail>
            <Detail label="Configuration Updated">{formatDateTime(project.updatedAt, tz)}</Detail>
          </dl>
        </Card>
      </div>

      <Card className="overflow-hidden">
        <div className="border-b border-slate-200 px-4 py-3">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <h2 className="text-sm font-semibold text-slate-900">Health Check History</h2>
            <nav className="flex flex-wrap items-center gap-1" aria-label="Filter history by status">
              {filterTabs.map((tab) => {
                const active = statusParam === tab.key;
                return (
                  <Link
                    key={tab.key}
                    href={historyHref(project.id, { status: tab.key, page: 1 })}
                    aria-current={active ? "true" : undefined}
                    className={cn(
                      "inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-xs font-medium whitespace-nowrap transition-colors",
                      active ? "bg-slate-900 text-white" : "text-slate-600 hover:bg-slate-100 hover:text-slate-900",
                    )}
                  >
                    {tab.label}
                    {tab.count !== null && (
                      <span className={cn("tabular-nums", active ? "text-slate-300" : "text-slate-400")}>{tab.count}</span>
                    )}
                  </Link>
                );
              })}
            </nav>
          </div>
          {recent.length > 1 && (
            <div className="mt-3">
              <StatusTimeline outcomes={recent} tz={tz} />
            </div>
          )}
        </div>

        {total === 0 ? (
          <div className="px-4 py-12 text-center">
            {historyStatus ? (
              <p className="text-sm text-slate-500">No {STATUS_LABELS[historyStatus].toLowerCase()} checks recorded.</p>
            ) : (
              <>
                <p className="text-sm font-medium text-slate-900">No health-check data available yet.</p>
                <p className="mt-1 text-sm text-slate-500">The first scheduled check will appear here.</p>
              </>
            )}
          </div>
        ) : (
          <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}>
                    Checked At
                  </th>
                  <th scope="col" className={th}>
                    Status
                  </th>
                  <th scope="col" className={`${th} text-right`}>
                    HTTP
                  </th>
                  <th scope="col" className={`${th} text-right`}>
                    Response Time
                  </th>
                  <th scope="col" className={th}>
                    Error
                  </th>
                  <th scope="col" className={th}>
                    Trigger
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {checks.map((check) => (
                  <tr key={check.id} className={cn(check.status !== "WORKING" && STATUS_STYLES[check.status].row)}>
                    <td className={`${td} text-xs text-slate-700`}>{formatDateTime(check.checkedAt, tz)}</td>
                    <td className={td}>
                      <StatusBadge status={check.status} />
                    </td>
                    <td className={`${td} text-right tabular-nums text-slate-700`}>{check.httpStatusCode ?? dash}</td>
                    <td className={cn(td, "text-right tabular-nums", check.status === "SLOW" ? "font-medium text-amber-700" : "text-slate-700")}>
                      {check.responseTimeMs !== null ? formatResponseTime(check.responseTimeMs) : dash}
                    </td>
                    <td className={cn(td, "text-xs", check.status === "SLOW" ? "text-amber-700" : "text-red-700")}>
                      {check.errorMessage ? (
                        <span className="block max-w-96 truncate" title={check.errorMessage}>
                          {check.errorMessage}
                        </span>
                      ) : (
                        dash
                      )}
                    </td>
                    <td className={`${td} text-xs text-slate-500`}>
                      {check.trigger === "MANUAL" ? "Manual" : "Scheduled"}
                      {check.attempts > 1 && <span title="The first attempt failed; this is the retry's result"> · retried</span>}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        <Pagination
          page={page}
          pageCount={pageCount}
          total={total}
          pageSize={HISTORY_PAGE_SIZE}
          hrefFor={(p) => historyHref(project.id, { status: statusParam, page: p })}
        />
      </Card>
    </>
  );
}
