import { notFound } from "next/navigation";
import Link from "next/link";
import { AdminPageHeader } from "@/components/admin/AdminBreadcrumbs";
import { StatusBadge } from "@/components/admin/StatusBadge";
import { EmptyState } from "@/components/admin/EmptyState";
import { formatDate } from "@/lib/client-api";
import { adminUserService } from "@/modules/admin";
import { activityService } from "@/modules/activity";
import { eventService } from "@/modules/events";
import { subscriptionService } from "@/modules/subscriptions";
import { UserControls } from "./user-controls";
import { ChangePlanControl } from "./change-plan-control";

export const dynamic = "force-dynamic";

export default async function AdminUserDetailPage({
  params,
}: {
  params: Promise<{ userId: string }>;
}) {
  const { userId } = await params;
  const user = await adminUserService.findById(userId);
  if (!user) notFound();

  const [events, subs, activity, activePlans] = await Promise.all([
    eventService.listForUser(userId),
    subscriptionService.listForUser(userId),
    activityService.listForUser(userId, 50),
    import("@/modules/pricing").then((m) => m.pricingService.listActive()),
  ]);

  const stats = {
    total: events.length,
    upcoming: events.filter((e) => e.status === "upcoming").length,
    completed: events.filter((e) => e.status === "completed").length,
    draft: events.filter((e) => e.status === "draft").length,
    cancelled: events.filter((e) => e.status === "cancelled").length,
  };
  const activeSub = subs.find(
    (s) => s.status === "active" || s.status === "trial",
  );

  return (
    <div className="space-y-6">
      <AdminPageHeader
        breadcrumbs={[
          { label: "Admin", href: "/admin" },
          { label: "Users", href: "/admin/users" },
          { label: user.name },
        ]}
        title={user.name}
        description={user.email}
        actions={
          <Link
            href="/admin/users"
            className="rounded-lg border border-border bg-surface px-3 py-1.5 text-sm font-medium text-foreground hover:bg-surface-muted"
          >
            ← Back to users
          </Link>
        }
      />

      <section className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <div className="rounded-2xl border border-border bg-surface p-5 shadow-sm">
          <p className="text-xs font-medium uppercase tracking-wide text-muted">Status</p>
          <div className="mt-2">
            <StatusBadge status={user.status} />
          </div>
          <p className="mt-2 text-xs text-muted capitalize">Role: {user.role.replace("_", " ")}</p>
        </div>
        <div className="rounded-2xl border border-border bg-surface p-5 shadow-sm">
          <p className="text-xs font-medium uppercase tracking-wide text-muted">Plan</p>
          <p className="mt-2 text-base font-semibold text-foreground">
            {user.plan ?? "—"}
          </p>
          <p className="mt-1 text-xs text-muted">
            {user.planStatus ? `Status: ${user.planStatus}` : "No subscription"}
          </p>
        </div>
        <div className="rounded-2xl border border-border bg-surface p-5 shadow-sm">
          <p className="text-xs font-medium uppercase tracking-wide text-muted">Events</p>
          <p className="mt-2 text-base font-semibold text-foreground">{stats.total}</p>
          <p className="mt-1 text-xs text-muted">
            {stats.upcoming} upcoming · {stats.completed} completed
          </p>
        </div>
        <div className="rounded-2xl border border-border bg-surface p-5 shadow-sm">
          <p className="text-xs font-medium uppercase tracking-wide text-muted">Joined</p>
          <p className="mt-2 text-base font-semibold text-foreground">
            {formatDate(user.createdAt)}
          </p>
          <p className="mt-1 text-xs text-muted">
            Last login: {formatDate(user.lastLoginAt)}
          </p>
        </div>
      </section>

      <section className="grid gap-6 lg:grid-cols-3">
        <div className="rounded-2xl border border-border bg-surface p-5 shadow-sm lg:col-span-2">
          <h2 className="text-sm font-semibold text-foreground">Profile</h2>
          <dl className="mt-4 grid gap-3 sm:grid-cols-2 text-sm">
            <div>
              <dt className="text-xs text-muted">Name</dt>
              <dd className="font-medium">{user.name}</dd>
            </div>
            <div>
              <dt className="text-xs text-muted">Email</dt>
              <dd className="font-medium break-all">{user.email}</dd>
            </div>
            <div>
              <dt className="text-xs text-muted">Auth providers</dt>
              <dd className="font-medium">
                {user.authProviders.length > 0
                  ? user.authProviders.join(", ")
                  : "—"}
              </dd>
            </div>
            <div>
              <dt className="text-xs text-muted">Email verified</dt>
              <dd className="font-medium">{user.emailVerified ? "Yes" : "No"}</dd>
            </div>
            <div>
              <dt className="text-xs text-muted">Updated</dt>
              <dd className="font-medium">{formatDate(user.updatedAt)}</dd>
            </div>
            <div>
              <dt className="text-xs text-muted">Google linked</dt>
              <dd className="font-medium">{user.googleId ? "Yes" : "No"}</dd>
            </div>
          </dl>
        </div>

        <div className="rounded-2xl border border-border bg-surface p-5 shadow-sm">
          <h2 className="text-sm font-semibold text-foreground">Security</h2>
          <ul className="mt-4 space-y-2 text-sm">
            <li className="flex items-center justify-between">
              <span className="text-muted">Two-factor</span>
              <span className="text-xs">Not enabled</span>
            </li>
            <li className="flex items-center justify-between">
              <span className="text-muted">Password set</span>
              <span className="text-xs">
                {user.authProviders.includes("credentials") ? "Yes" : "No"}
              </span>
            </li>
            <li className="flex items-center justify-between">
              <span className="text-muted">Failed logins</span>
              <span className="text-xs">Tracked in audit</span>
            </li>
          </ul>
        </div>
      </section>

      <section className="grid gap-6 lg:grid-cols-3">
        <div className="rounded-2xl border border-border bg-surface p-5 shadow-sm">
          <h2 className="text-sm font-semibold text-foreground">Subscription</h2>
          {activeSub ? (
            <div className="mt-4 space-y-2 text-sm">
              <p>
                <span className="text-muted">Plan: </span>
                <span className="font-medium">{activeSub.planName}</span>
              </p>
              <p>
                <span className="text-muted">Status: </span>
                <StatusBadge status={activeSub.status} />
              </p>
              <p>
                <span className="text-muted">Started: </span>
                {formatDate(activeSub.startDate)}
              </p>
              <p>
                <span className="text-muted">Renews/ends: </span>
                {formatDate(activeSub.endDate)}
              </p>
              <p>
                <span className="text-muted">Usage: </span>
                {activeSub.usage.events} events · {activeSub.usage.guests} guests
              </p>
            </div>
          ) : (
            <p className="mt-4 text-sm text-muted">No active subscription.</p>
          )}
          <ChangePlanControl
            userId={userId}
            currentPlanSlug={activeSub?.planSlug ?? null}
            plans={activePlans}
          />
        </div>

        <div className="rounded-2xl border border-border bg-surface p-5 shadow-sm">
          <h2 className="text-sm font-semibold text-foreground">Events</h2>
          {events.length === 0 ? (
            <EmptyState title="No events" />
          ) : (
            <ul className="mt-3 space-y-2">
              {events.slice(0, 5).map((e) => (
                <li
                  key={e.id}
                  className="flex items-center justify-between gap-2 rounded-lg border border-border p-2"
                >
                  <div className="min-w-0">
                    <p className="truncate text-sm font-medium text-foreground">
                      {e.title}
                    </p>
                    <p className="text-xs text-muted">
                      {formatDate(e.eventDate)}
                    </p>
                  </div>
                  <StatusBadge status={e.status} />
                </li>
              ))}
            </ul>
          )}
        </div>

        <div className="rounded-2xl border border-border bg-surface p-5 shadow-sm">
          <h2 className="text-sm font-semibold text-foreground">Activity</h2>
          {activity.length === 0 ? (
            <EmptyState title="No activity yet" />
          ) : (
            <ol className="mt-3 space-y-3 border-l border-border pl-3">
              {activity.map((a) => (
                <li key={a.id} className="relative">
                  <span className="absolute -left-[7px] top-1.5 grid h-3 w-3 place-items-center rounded-full bg-primary" />
                  <p className="text-sm font-medium text-foreground">
                    {a.message}
                  </p>
                  <p className="text-xs text-muted">
                    {a.type} · {formatDate(a.createdAt)}
                  </p>
                </li>
              ))}
            </ol>
          )}
        </div>
      </section>

      <UserControls
        userId={userId}
        email={user.email}
        status={user.status}
      />
    </div>
  );
}