import Link from "next/link";
import { redirect } from "next/navigation";
import {
  addDomainAction,
  deleteDomainAction,
} from "@/app/dashboard/actions";
import { CopyTextButton } from "@/components/dashboard/copy-text-button";
import { DashboardPageHeader } from "@/components/dashboard/page-header";
import { DashboardShell } from "@/components/dashboard/dashboard-shell";
import { requireDashboardContext } from "@/core/auth/dashboard-context";
import {
  buildTenantSubdomainUrl,
  getTenantPublicHostLabel,
} from "@/core/config/domains";
import { getRequestHostname } from "@/core/tenant/request-tenant";
import { listTenantDomains } from "@/services/domain-service";

export default async function DashboardDomainsPage() {
  const ctx = await requireDashboardContext("domains:manage");
  const requestHost = await getRequestHostname();
  const siteUrl = buildTenantSubdomainUrl(ctx.tenant.tenantSlug, {
    requestHost,
  });
  const hostLabel = getTenantPublicHostLabel(ctx.tenant.tenantSlug, {
    requestHost,
  });
  const rows = await listTenantDomains(ctx.tenant);
  const customDomains = rows.filter((row) => row.type === "custom");

  async function addDomain(formData: FormData) {
    "use server";
    const result = await addDomainAction(formData);
    if (!result.ok) {
      redirect("/dashboard/domains?error=1");
    }
    redirect("/dashboard/domains?added=1");
  }

  return (
    <DashboardShell width="wide">
      <DashboardPageHeader
        eyebrow="Studio"
        title="Domains"
        description="Manage your live subdomain and attach custom domains for verification."
      />

      <div className="mt-8 grid gap-4 lg:grid-cols-2">
        <div className="rounded-2xl border border-[var(--archi-line)] bg-white/80 p-5">
          <p className="text-xs tracking-[0.2em] text-[var(--archi-ink-muted)] uppercase">
            Live subdomain
          </p>
          <p className="mt-2 font-[family-name:var(--font-display)] text-2xl">
            {hostLabel}
          </p>
          <div className="mt-4 flex flex-wrap gap-2">
            <CopyTextButton text={hostLabel} label="Copy host" />
            <CopyTextButton text={siteUrl} label="Copy URL" />
            <a
              href={siteUrl}
              target="_blank"
              rel="noreferrer"
              className="inline-flex items-center border border-[var(--archi-line)] bg-white px-3 py-1.5 text-xs font-medium"
            >
              Open site ↗
            </a>
          </div>
        </div>

        <form
          action={addDomain}
          className="rounded-2xl border border-[var(--archi-line)] bg-white/80 p-5"
        >
          <p className="text-xs tracking-[0.2em] text-[var(--archi-ink-muted)] uppercase">
            Add custom domain
          </p>
          <p className="mt-2 text-sm text-[var(--archi-ink-muted)]">
            Domain starts as pending until DNS verification completes.
          </p>
          <label className="mt-4 block text-sm">
            Domain name
            <input
              name="domain"
              required
              placeholder="studio.example.com"
              className="mt-2 w-full border border-[var(--archi-line)] bg-white px-3 py-2"
            />
          </label>
          <button type="submit" className="archi-btn-primary mt-4">
            Add domain
          </button>
        </form>
      </div>

      <div className="mt-8">
        <h2 className="font-[family-name:var(--font-display)] text-xl">
          All domains
        </h2>
        {rows.length === 0 ? (
          <p className="mt-4 text-sm text-[var(--archi-ink-muted)]">
            No domain records found.
          </p>
        ) : (
          <ul className="mt-4 space-y-3">
            {rows.map((row) => (
              <li
                key={row.id}
                className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-[var(--archi-line)] bg-white/80 px-4 py-3 text-sm"
              >
                <div>
                  <p className="font-medium">{row.domain}</p>
                  <p className="text-xs text-[var(--archi-ink-muted)]">
                    {row.type} · verification {row.verificationStatus} · SSL{" "}
                    {row.sslStatus}
                    {row.isPrimary ? " · primary" : ""}
                  </p>
                  {row.type === "custom" && row.verificationToken ? (
                    <p className="mt-1 text-xs text-[var(--archi-ink-muted)]">
                      Verification token:{" "}
                      <code className="text-[11px]">{row.verificationToken}</code>
                    </p>
                  ) : null}
                </div>
                <div className="flex gap-2">
                  <CopyTextButton text={row.domain} label="Copy" />
                  {row.type === "custom" ? (
                    <form action={deleteDomainAction.bind(null, row.id)}>
                      <button
                        type="submit"
                        className="text-xs text-red-800 underline"
                      >
                        Remove
                      </button>
                    </form>
                  ) : null}
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>

      {customDomains.length > 0 ? (
        <p className="mt-6 text-xs text-[var(--archi-ink-muted)]">
          {customDomains.length} custom domain
          {customDomains.length === 1 ? "" : "s"} pending or configured.
        </p>
      ) : null}
    </DashboardShell>
  );
}
