import type { Metadata } from "next";
import { desc } from "drizzle-orm";
import { Route, Trash2, Power, PowerOff, RefreshCw } from "lucide-react";
import { requireAdmin } from "@/lib/auth/admin-guard";
import { db } from "@/lib/db/client";
import { redirects } from "@/lib/db/schema";
import {
  AdminHeading,
  FormSection,
  InputField,
  SelectField,
  TextareaField,
  StatusBadge,
  DataTable,
  KpiCard,
  EmptyState,
  formatAdminDateTime,
  type Column,
} from "@/components/admin";
import { Button } from "@/components/Button";
import {
  createRedirect,
  toggleRedirect,
  deleteRedirect,
  refreshRedirectCache,
} from "./actions";
import type { Redirect } from "@/lib/db/schema";

export const metadata: Metadata = { title: "Redirects" };
export const dynamic = "force-dynamic";

export default async function AdminRedirectsPage() {
  await requireAdmin();
  const rows = await db.select().from(redirects).orderBy(desc(redirects.createdAt));
  const active = rows.filter((r) => r.active).length;
  const hits = rows.reduce((a, r) => a + r.hits, 0);

  const columns: Column<Redirect>[] = [
    {
      key: "source",
      header: "Source",
      cell: (r) => (
        <code className="font-mono text-[12px] text-[var(--color-ink)]">
          {r.source}
        </code>
      ),
    },
    {
      key: "destination",
      header: "Destination",
      cell: (r) => (
        <code className="font-mono text-[12px] text-[var(--color-blue)]">
          {r.destination}
        </code>
      ),
      className: "truncate max-w-[300px]",
    },
    {
      key: "type",
      header: "Type",
      cell: (r) => (
        <StatusBadge
          label={r.kind === "permanent" ? "301" : "302"}
          tone={r.kind === "permanent" ? "info" : "muted"}
        />
      ),
      className: "whitespace-nowrap",
    },
    {
      key: "active",
      header: "Active",
      cell: (r) => (
        <StatusBadge
          label={r.active ? "on" : "off"}
          tone={r.active ? "success" : "muted"}
          dot
        />
      ),
      className: "whitespace-nowrap",
    },
    {
      key: "hits",
      header: "Hits",
      cell: (r) => r.hits,
      className: "tabular-nums text-right",
      align: "right",
    },
    {
      key: "last",
      header: "Last hit",
      cell: (r) =>
        r.lastHitAt ? (
          formatAdminDateTime(r.lastHitAt)
        ) : (
          <span className="text-[var(--color-slate)]">—</span>
        ),
      className: "whitespace-nowrap text-[12px] text-[var(--color-slate)]",
    },
    {
      key: "actions",
      header: "",
      align: "right",
      cell: (r) => (
        <div className="flex items-center justify-end gap-1">
          <form action={toggleRedirect}>
            <input type="hidden" name="id" value={r.id} />
            <input type="hidden" name="active" value={r.active ? "0" : "1"} />
            <button
              type="submit"
              title={r.active ? "Disable" : "Enable"}
              aria-label={`${r.active ? "Disable" : "Enable"} redirect from ${r.source}`}
              className="rounded-md p-1.5 text-[var(--color-slate)] hover:bg-[var(--color-mist)] hover:text-[var(--color-blue)]"
            >
              {r.active ? (
                <PowerOff className="h-4 w-4" aria-hidden />
              ) : (
                <Power className="h-4 w-4" aria-hidden />
              )}
            </button>
          </form>
          <form action={deleteRedirect}>
            <input type="hidden" name="id" value={r.id} />
            <button
              type="submit"
              title="Delete"
              aria-label={`Delete redirect from ${r.source}`}
              className="rounded-md p-1.5 text-[var(--color-slate)] hover:bg-red-50 hover:text-red-600"
            >
              <Trash2 className="h-4 w-4" aria-hidden />
            </button>
          </form>
        </div>
      ),
      className: "whitespace-nowrap",
    },
  ];

  return (
    <>
      <AdminHeading
        eyebrow="System"
        title="Redirects"
        lede="Manage 301/302 URL redirects. Applied by the proxy before any page renders. Changes you make here take effect immediately; the cache below only needs refreshing if you edited the database directly."
        actions={
          <form action={refreshRedirectCache}>
            <Button
              type="submit"
              variant="secondary"
              className="!px-3 !py-1.5 !text-[13px]"
            >
              <RefreshCw className="h-3.5 w-3.5" aria-hidden />
              Refresh proxy cache
            </Button>
          </form>
        }
      />

      <div className="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-3">
        <KpiCard label="Total" value={rows.length} tone="ink" Icon={Route} />
        <KpiCard label="Active" value={active} tone="emerald" />
        <KpiCard label="Total hits" value={hits} tone="blue" />
      </div>

      <FormSection
        title="New redirect"
        description="Source is the path visitors reach; destination is where they land. 301 is permanent (SEO), 302 is temporary."
      >
        <form action={createRedirect} className="grid gap-3 md:grid-cols-[1fr_1fr_auto_auto]">
          <InputField
            label="Source"
            name="source"
            placeholder="/old-path"
            required
            maxLength={400}
          />
          <InputField
            label="Destination"
            name="destination"
            placeholder="/new-path or https://…"
            required
            maxLength={1000}
          />
          <SelectField
            label="Type"
            name="kind"
            defaultValue="permanent"
            options={[
              { value: "permanent", label: "301 Permanent" },
              { value: "temporary", label: "302 Temporary" },
            ]}
          />
          <div className="flex items-end">
            <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
              Add redirect
            </Button>
          </div>
          <div className="md:col-span-4">
            <TextareaField
              label="Notes (internal)"
              name="notes"
              rows={2}
              maxLength={500}
              placeholder="Optional reason, e.g. 'Retired blog post — points to new series index'"
            />
          </div>
        </form>
      </FormSection>

      <div className="mt-8">
        {rows.length === 0 ? (
          <EmptyState
            Icon={Route}
            title="No redirects yet"
            description="Add your first redirect above."
          />
        ) : (
          <DataTable columns={columns} rows={rows} rowKey={(r) => r.id} />
        )}
      </div>
    </>
  );
}
