import type { Metadata } from "next";
import Link from "next/link";
import { Pencil, Plus, Search } from "lucide-react";
import { RunInProgress } from "@/components/dashboard/run-in-progress";
import { CheckDomainsButton } from "@/components/domains/check-domains-button";
import { DeleteDomainButton } from "@/components/domains/delete-domain-button";
import { DomainAppsButton } from "@/components/domains/domain-apps-button";
import { DOMAIN_STATUS_STYLES, DomainStatusBadge } from "@/components/domains/domain-status-badge";
import { RestoreDomainButton } from "@/components/domains/restore-domain-button";
import { PageHeader } from "@/components/layout/page-header";
import { Button } from "@/components/ui/button";
import { ButtonLink } from "@/components/ui/button-link";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/cn";
import {
  DOMAIN_FILTERS,
  DOMAIN_FILTER_KEYS,
  DOMAIN_SOURCES,
  domainsHref,
  filterDomainRows,
  parseDomainQuery,
  type DomainFilter,
} from "@/lib/domains/query";
import { CRITICAL_DAYS, DOMAIN_STATUS_LABELS, WARNING_DAYS, formatDaysLeft, riskyRegistryStatuses } from "@/lib/domains/status";
import { formatDate, formatDateTime } from "@/lib/format";
import { canEdit } from "@/lib/auth/roles";
import { requireUser } from "@/server/auth/session";
import { getActiveDomainRun, getLastDomainRun } from "@/server/domains/run";
import { getDomainOverview, type DomainOverviewRow } from "@/server/domains/service";
import { getMonitoringSettings } from "@/server/settings/service";

export const metadata: Metadata = { title: "Domains" };

type DomainsPageProps = { 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-top";
const dash = <span className="text-slate-300">—</span>;
const MAX_APPS_SHOWN = 3;

// Summary cards double as filter links, like the dashboard's.
const SUMMARY: Array<{ filter: DomainFilter; label: string; dot: string; emphasis: string }> = [
  { filter: "expired", label: "Expired / Not Registered", dot: "bg-red-500", emphasis: "text-red-700" },
  { filter: "critical", label: `Critical (≤ ${CRITICAL_DAYS} days)`, dot: "bg-red-500", emphasis: "text-red-700" },
  { filter: "warning", label: `Expiring Soon (≤ ${WARNING_DAYS} days)`, dot: "bg-amber-500", emphasis: "text-amber-700" },
  { filter: "unknown", label: "Unknown / Not checked", dot: "bg-slate-500", emphasis: "text-slate-900" },
  { filter: "ok", label: "OK", dot: "bg-emerald-500", emphasis: "text-slate-900" },
];

/** The first few app codes; clicking anywhere on them lists every app on the domain. */
function AppLinks({ domain, apps }: { domain: string; apps: DomainOverviewRow["apps"] }) {
  const more = apps.length - MAX_APPS_SHOWN;
  return (
    <DomainAppsButton domain={domain} apps={apps} className="text-xs text-slate-700 hover:text-slate-900">
      {apps
        .slice(0, MAX_APPS_SHOWN)
        .map((app) => app.projectCode)
        .join(", ")}
      {more > 0 && <span className="font-medium text-slate-500 hover:text-slate-900"> +{more} more</span>}
    </DomainAppsButton>
  );
}

export default async function DomainsPage({ searchParams }: DomainsPageProps) {
  const editable = canEdit(await requireUser());

  const query = parseDomainQuery(await searchParams);
  const [{ rows, hidden, withoutDomain }, activeRun, lastRun, settings] = await Promise.all([
    getDomainOverview(),
    getActiveDomainRun(),
    getLastDomainRun(),
    getMonitoringSettings(),
  ]);
  const tz = settings.timezone;
  const { shown, total, counts } = filterDomainRows(rows, query);
  const filtered = query.status !== null || query.source !== "all" || query.q !== "";
  const summaryCount = (filter: DomainFilter) => rows.filter((row) => DOMAIN_FILTERS[filter].matches(row.status)).length;

  return (
    <>
      <PageHeader
        title="Domains"
        actions={
          editable && (
            <>
              <CheckDomainsButton running={Boolean(activeRun)} />
              <ButtonLink href="/domains/new" variant="secondary">
                <Plus className="size-4" aria-hidden />
                Add Domain
              </ButtonLink>
            </>
          )
        }
      />

      {activeRun && (
        <RunInProgress
          label={`Domain check in progress — started ${formatDateTime(activeRun.startedAt, tz)}${activeRun.startedBy ? ` by ${activeRun.startedBy}` : ""}.`}
        />
      )}

      <div className="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-5">
        {SUMMARY.map((card) => {
          const value = summaryCount(card.filter);
          return (
            <Link
              key={card.filter}
              href={domainsHref(query, { status: card.filter })}
              aria-label={`${card.label}: ${value}. Show in table.`}
              className={cn(
                "rounded-lg border bg-white px-4 py-3 transition-colors hover:border-slate-400",
                "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-900",
                query.status === card.filter ? "border-slate-900" : "border-slate-200",
              )}
            >
              <p className="flex items-center gap-1.5 text-xs font-medium text-slate-500">
                <span className={cn("size-1.5 shrink-0 rounded-full", card.dot)} aria-hidden />
                <span className="truncate">{card.label}</span>
              </p>
              <p className={cn("mt-1 text-2xl font-semibold tabular-nums", value > 0 ? card.emphasis : "text-slate-900")}>{value}</p>
            </Link>
          );
        })}
      </div>

      <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">Domain Expiry</h2>
          <p className="text-xs text-slate-500">
            Checked daily at {settings.checkTime} ({tz}) ·{" "}
            {lastRun
              ? `Last check: ${formatDateTime(lastRun.startedAt, tz)}${lastRun.status === "FAILED" ? " (failed)" : ""}`
              : "Not checked yet"}
          </p>
        </div>

        <div className="flex flex-wrap items-center justify-between gap-3 border-b border-slate-200 px-4 py-3">
          <nav className="flex flex-wrap items-center gap-1" aria-label="Filter by status">
            {[{ key: null, label: "All", count: total }, ...DOMAIN_FILTER_KEYS.map((key) => ({ key, label: DOMAIN_FILTERS[key].label, count: counts[key] }))].map(
              (tab) => {
                const active = query.status === tab.key;
                return (
                  <Link
                    key={tab.label}
                    href={domainsHref(query, { status: tab.key })}
                    aria-current={active ? "true" : undefined}
                    className={cn(
                      "inline-flex h-8 items-center gap-1.5 rounded-md px-2.5 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}
                    <span className={cn("tabular-nums", active ? "text-slate-300" : "text-slate-400")}>{tab.count}</span>
                  </Link>
                );
              },
            )}
          </nav>

          <form action="/domains" className="flex flex-wrap items-center gap-2" role="search">
            {/* Keep the current status tab when searching. */}
            {query.status && <input type="hidden" name="status" value={query.status} />}
            <select
              name="source"
              defaultValue={query.source}
              aria-label="Filter by source"
              className="h-9 rounded-md border border-slate-300 bg-white px-2 text-sm text-slate-700 focus-visible:outline-2 focus-visible:outline-slate-900"
            >
              {Object.entries(DOMAIN_SOURCES).map(([value, label]) => (
                <option key={value} value={value}>
                  {label}
                </option>
              ))}
            </select>
            <div className="relative w-64 max-w-full">
              <Search className="pointer-events-none absolute top-2.5 left-2.5 size-4 text-slate-400" aria-hidden />
              <Input
                name="q"
                type="search"
                defaultValue={query.q}
                placeholder="Domain, registrar or app"
                aria-label="Search by domain, registrar, or app code or name"
                className="pl-8"
              />
            </div>
            <Button type="submit" variant="secondary">
              Search
            </Button>
            {filtered && (
              <Link href="/domains" className="text-xs font-medium text-slate-500 hover:text-slate-900">
                Clear
              </Link>
            )}
          </form>
        </div>

        {shown.length === 0 ? (
          <p className="px-4 py-10 text-center text-sm text-slate-500">
            {rows.length === 0
              ? `No domains to watch. Domains appear here once monitored apps have a health API URL on a registered domain${editable ? ", or when you add one" : ""}.`
              : "No domains match this filter."}
          </p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[76rem] border-collapse text-sm whitespace-nowrap">
              <thead className="border-b border-slate-200 bg-slate-50">
                <tr>
                  <th scope="col" className={th}>Domain</th>
                  <th scope="col" className={th}>Status</th>
                  <th scope="col" className={th}>Expires</th>
                  <th scope="col" className={th}>Registered</th>
                  <th scope="col" className={th}>Last Changed</th>
                  <th scope="col" className={th}>Registrar</th>
                  <th scope="col" className={th}>Apps</th>
                  <th scope="col" className={th}>Last Checked</th>
                  {editable && (
                    <th scope="col" className={th}>
                      <span className="sr-only">Actions</span>
                    </th>
                  )}
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {shown.map((row) => {
                  const { domain } = row;
                  const risky = riskyRegistryStatuses(domain?.registryStatuses ?? []);
                  const noRegistryExpiry = domain && !domain.expiresAt && domain.lastLookupResult === "FOUND";
                  return (
                    <tr key={row.name} className={DOMAIN_STATUS_STYLES[row.status].row}>
                      <td className={td}>
                        {row.apps.length > 0 ? (
                          <DomainAppsButton domain={row.name} apps={row.apps} className="font-medium text-slate-900">
                            {row.name}
                          </DomainAppsButton>
                        ) : (
                          <span className="font-medium text-slate-900">{row.name}</span>
                        )}
                        {risky.length > 0 && (
                          <span className="block text-xs font-medium text-red-700">Registry: {risky.join(", ")}</span>
                        )}
                      </td>
                      <td className={td}>
                        <DomainStatusBadge status={row.status} />
                      </td>
                      <td className={`${td} text-xs`}>
                        {row.expiry ? (
                          <>
                            <span className="text-slate-900">{formatDate(row.expiry, tz)}</span>
                            {row.daysLeft !== null && (
                              <span className={cn("block", DOMAIN_STATUS_STYLES[row.status].text)}>
                                {row.status === "EXPIRED" ? "expired " : ""}
                                {formatDaysLeft(row.daysLeft)}
                                {row.expirySource === "manual" && <span className="text-slate-500"> · entered manually</span>}
                              </span>
                            )}
                          </>
                        ) : noRegistryExpiry ? (
                          <>
                            <span className="block text-slate-500">Not published by the registry</span>
                            {editable && (
                              <Link href={`/domains/${domain.id}/edit`} className="font-medium text-slate-900 underline decoration-slate-300 underline-offset-2 hover:decoration-slate-900">
                                Set expiry date
                              </Link>
                            )}
                          </>
                        ) : (
                          dash
                        )}
                      </td>
                      <td className={`${td} text-xs text-slate-700`}>{domain?.registeredAt ? formatDate(domain.registeredAt, tz) : dash}</td>
                      <td className={`${td} text-xs text-slate-700`}>{domain?.lastChangedAt ? formatDate(domain.lastChangedAt, tz) : dash}</td>
                      <td className={`${td} text-xs text-slate-700`}>
                        {domain?.registrar ? (
                          <span className="block max-w-48 truncate" title={domain.registrar}>
                            {domain.registrar}
                          </span>
                        ) : (
                          dash
                        )}
                      </td>
                      <td className={td}>
                        {row.apps.length > 0 ? <AppLinks domain={row.name} apps={row.apps} /> : <span className="text-xs text-slate-500">Added manually</span>}
                      </td>
                      <td className={`${td} text-xs text-slate-600`}>
                        {domain?.lastCheckedAt ? formatDateTime(domain.lastCheckedAt, tz) : DOMAIN_STATUS_LABELS.PENDING}
                        {domain?.lastLookupError && (
                          <span className="block max-w-72 truncate text-red-700" title={domain.lastLookupError}>
                            {domain.lastLookupError}
                          </span>
                        )}
                      </td>
                      {editable && (
                      <td className={`${td} text-right`}>
                        {domain && (
                          <span className="inline-flex items-center gap-1">
                            <ButtonLink
                              href={`/domains/${domain.id}/edit`}
                              variant="secondary"
                              className="h-8 px-3 text-xs"
                              aria-label={`Edit ${row.name}`}
                            >
                              <Pencil className="size-3.5" aria-hidden />
                              Edit
                            </ButtonLink>
                            <DeleteDomainButton id={domain.id} name={row.name} appCount={row.apps.length} />
                          </span>
                        )}
                      </td>
                      )}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        {withoutDomain.length > 0 && (
          <p className="border-t border-slate-200 px-4 py-3 text-xs text-slate-500">
            Not listed — no registered domain in the health API URL (IP address or internal host):{" "}
            {withoutDomain.map((app, index) => (
              <span key={app.id}>
                {index > 0 && ", "}
                <Link href={`/apps/${app.id}`} title={app.projectName} className="text-slate-700 hover:underline">
                  {app.projectCode}
                </Link>
              </span>
            ))}
          </p>
        )}
      </Card>

      {hidden.length > 0 && (
        <details className="mt-4 rounded-lg border border-slate-200 bg-white">
          <summary className="cursor-pointer px-4 py-3 text-sm font-semibold text-slate-900">
            Hidden domains <span className="font-normal text-slate-500">({hidden.length})</span>
          </summary>
          <ul className="divide-y divide-slate-100 border-t border-slate-200">
            {hidden.map((row) => (
              <li key={row.name} className="flex flex-wrap items-center justify-between gap-3 px-4 py-2.5">
                <span className="text-sm">
                  <span className="font-medium text-slate-900">{row.name}</span>
                  <span className="ml-2 text-xs text-slate-500">
                    {row.apps.length > 0 ? <AppLinks domain={row.name} apps={row.apps} /> : "Added manually"} · hidden{" "}
                    {row.domain?.hiddenAt ? formatDateTime(row.domain.hiddenAt, tz) : ""} · not checked while hidden
                  </span>
                </span>
                {editable && row.domain && <RestoreDomainButton id={row.domain.id} name={row.name} />}
              </li>
            ))}
          </ul>
        </details>
      )}
    </>
  );
}
