import {
  CalendarClock,
  Fingerprint,
  Globe2,
  KeyRound,
  Languages,
  Mail,
  ShieldCheck,
  UserRound,
  Users,
} from "lucide-react";
import Link from "next/link";

import { ListPageCard } from "@/app/dashboard/_components";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

import { fetchBackendRoles } from "@/app/dashboard/admins/access/roles/_lib/roles-server-api";
import { fetchBackendUser, type UserDetail } from "../_lib/users-server-api";
import { ActiveInactiveBadge } from "@/components/shared/status-pill";
import { UserUpdateForm } from "../_components/user-form/user-create-form";
import { DeleteUserPageClient } from "./_components/delete-user-page-client";
import { UserAccessPageClient } from "./_components/user-access-page-client";

type PageProps = {
  params: Promise<{
    userId: string;
  }>;
  searchParams: Promise<{
    action?: string;
  }>;
};

export default async function AdminUserDetailPage({ params, searchParams }: PageProps) {
  const { userId: rawUserId } = await params;
  const { action } = await searchParams;
  const userId = Number(decodeURIComponent(rawUserId));
  const { user, errorMessage } = await fetchBackendUser(userId);

  if (!user) {
    return (
      <ListPageCard
        icon={Users}
        title="User not found"
        breadcrumb={[
          { label: "Admins & Access", href: "/dashboard/admins/users" },
          { label: "Users", href: "/dashboard/admins/users" },
          { label: rawUserId },
        ]}
      >
        <p className="text-muted-foreground text-sm">
          {errorMessage ?? "The requested user does not exist."}
        </p>
      </ListPageCard>
    );
  }

  if (action === "update") {
    return <UserUpdateForm user={user} />;
  }

  if (action === "delete") {
    return (
      <ListPageCard
        icon={Users}
        title={`Delete user: ${user.displayName || user.email}`}
        breadcrumb={[
          { label: "Admins & Access", href: "/dashboard/admins/users" },
          { label: "Users", href: "/dashboard/admins/users" },
          { label: user.displayName || user.email },
          { label: "Delete" },
        ]}
      >
        <DeleteUserPageClient user={user} />
      </ListPageCard>
    );
  }

  if (action === "access") {
    const { roles, errorMessage: rolesErrorMessage } = await fetchBackendRoles();

    return (
      <ListPageCard
        icon={Users}
        title={`Manage access: ${user.displayName || user.email}`}
        description="Assign roles and review direct and effective permissions for this user."
        breadcrumb={[
          { label: "Admins & Access", href: "/dashboard/admins/users" },
          { label: "Users", href: "/dashboard/admins/users" },
          { label: user.displayName || user.email },
          { label: "Access" },
        ]}
      >
        <UserAccessPageClient
          user={user}
          roles={roles}
          rolesErrorMessage={rolesErrorMessage}
        />
      </ListPageCard>
    );
  }

  const assignedRoles = user.roles.length ? user.roles : user.roleLabels ?? [];

  return (
    <ListPageCard
      icon={Users}
      title={user.displayName || user.email}
      description="Live backend user details, access grants, and effective permissions."
      breadcrumb={[
        { label: "Admins & Access", href: "/dashboard/admins/users" },
        { label: "Users", href: "/dashboard/admins/users" },
        { label: user.displayName || user.email },
      ]}
      actions={
        <Button asChild size="sm" variant="outline">
          <Link href={`/dashboard/admins/users/${user.userId}?action=access`}>
            <KeyRound className="size-4" />
            Manage access
          </Link>
        </Button>
      }
    >
      <div className="space-y-5">
        <UserHero user={user} />

        <div className="grid gap-3 sm:grid-cols-3">
          <StatCard label="Roles" value={assignedRoles.length} helper="Assigned access groups" />
          <StatCard
            label="Direct grants"
            value={user.directPermissions.length}
            helper="User-specific permissions"
          />
          <StatCard
            label="Effective"
            value={user.effectivePermissions.length}
            helper="Total active permissions"
          />
        </div>

        <div className="grid gap-5 xl:grid-cols-[minmax(0,0.92fr)_minmax(0,1.08fr)]">
          <DetailSection
            title="Account Details"
            description="Identity, localization, and account activity."
          >
            <DetailItem icon={Fingerprint} label="User ID" value={String(user.userId)} mono />
            <DetailItem icon={ShieldCheck} label="UID" value={user.userUid || "-"} mono />
            <DetailItem icon={UserRound} label="Principal" value={user.principal} mono />
            <DetailItem icon={Globe2} label="Timezone" value={user.timezone || "-"} />
            <DetailItem icon={Languages} label="Language ID" value={user.languageId ?? "-"} />
            <DetailItem icon={Users} label="Group ID" value={user.groupId ?? "-"} />
            <DetailItem icon={CalendarClock} label="Date Added" value={user.dateAdded || "-"} />
            <DetailItem icon={CalendarClock} label="Last Updated" value={user.lastUpdated || "-"} />
            <DetailItem icon={CalendarClock} label="Last Login" value={user.lastLogin || "-"} />
          </DetailSection>

          <DetailSection
            title="Access Summary"
            description="Roles, direct grants, and merged effective permissions."
          >
            <TokenList
              label="Roles"
              values={assignedRoles}
              emptyText="No roles assigned"
              tone="primary"
            />
            <TokenList
              label="Direct Permissions"
              values={user.directPermissions}
              emptyText="No direct permissions"
              tone="warning"
            />
            <TokenList
              label="Effective Permissions"
              values={user.effectivePermissions}
              emptyText="No effective permissions"
              tone="success"
            />
          </DetailSection>
        </div>
      </div>
    </ListPageCard>
  );
}

function UserHero({ user }: { user: UserDetail }) {
  return (
    <div className="relative overflow-hidden rounded-3xl border bg-gradient-to-br from-primary/10 via-card to-card p-5 shadow-sm sm:p-6">
      <div className="absolute -right-16 -top-20 size-48 rounded-full bg-primary/10 blur-3xl" />
      <div className="absolute -bottom-24 left-1/3 size-56 rounded-full bg-blue-500/10 blur-3xl" />

      <div className="relative flex flex-wrap items-start gap-5">
        <Avatar className="size-20 border-4 border-background shadow-md">
          {user.avatarUrl ? <AvatarImage src={user.avatarUrl} alt="" /> : null}
          <AvatarFallback className="bg-primary text-primary-foreground text-xl">
            {initials(user.firstName, user.lastName)}
          </AvatarFallback>
        </Avatar>
        <div className="min-w-0 flex-1">
          <div className="flex flex-wrap items-center gap-2">
            <h2 className="font-semibold text-2xl tracking-tight">
              {user.displayName || user.email}
            </h2>
            <ActiveInactiveBadge status={user.status} label={user.statusLabel} />
            {user.isRemovable ? null : <Badge variant="secondary">Protected</Badge>}
          </div>
          <a
            href={`mailto:${user.email}`}
            className="mt-2 inline-flex items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-primary"
          >
            <Mail className="size-4" />
            <span className="break-all">{user.email}</span>
          </a>
          <div className="mt-4 flex flex-wrap gap-2">
            <Badge variant="outline" className="bg-background/70 backdrop-blur">
              {user.groupLabel}
            </Badge>
            {user.roles.map((role) => (
              <Badge key={role} variant="secondary" className="font-mono shadow-sm">
                {role}
              </Badge>
            ))}
          </div>
        </div>
        <div className="flex shrink-0 items-center gap-2 rounded-full border bg-background/80 px-3 py-2 text-muted-foreground text-sm shadow-sm backdrop-blur">
          <UserRound className="size-4" />
          <span className="font-mono">{user.principal}</span>
        </div>
      </div>
    </div>
  );
}

function StatCard({
  label,
  value,
  helper,
}: {
  label: string;
  value: number;
  helper: string;
}) {
  return (
    <div className="rounded-2xl border bg-card/80 p-4 shadow-sm transition-colors hover:bg-muted/30">
      <p className="text-muted-foreground text-sm">{label}</p>
      <div className="mt-2 flex items-end justify-between gap-3">
        <p className="font-semibold text-3xl tracking-tight">{value}</p>
        <KeyRound className="mb-1 size-5 text-primary" />
      </div>
      <p className="mt-2 text-muted-foreground text-xs">{helper}</p>
    </div>
  );
}

function DetailSection({
  title,
  description,
  children,
}: {
  title: string;
  description: string;
  children: React.ReactNode;
}) {
  return (
    <section className="rounded-3xl border bg-card p-5 shadow-sm">
      <div>
        <h3 className="font-semibold text-base">{title}</h3>
        <p className="mt-1 text-muted-foreground text-sm">{description}</p>
      </div>
      <div className="mt-5 space-y-3">{children}</div>
    </section>
  );
}

function DetailItem({
  icon: Icon,
  label,
  value,
  mono,
}: {
  icon: typeof Fingerprint;
  label: string;
  value: string;
  mono?: boolean;
}) {
  return (
    <div className="flex items-center gap-3 rounded-2xl border bg-muted/20 px-3 py-3 transition-colors hover:bg-muted/40">
      <div className="flex size-9 shrink-0 items-center justify-center rounded-xl bg-background text-muted-foreground shadow-sm">
        <Icon className="size-4" />
      </div>
      <div className="min-w-0 flex-1">
        <p className="text-muted-foreground text-xs">{label}</p>
        <p className={cn("mt-0.5 truncate text-sm", mono && "font-mono")}>{value}</p>
      </div>
    </div>
  );
}

function TokenList({
  label,
  values,
  emptyText,
  tone = "default",
}: {
  label: string;
  values: string[];
  emptyText: string;
  tone?: "default" | "primary" | "success" | "warning";
}) {
  const toneStyles = {
    default: "bg-muted/20",
    primary: "border-primary/20 bg-primary/5",
    success: "border-emerald-500/20 bg-emerald-500/5",
    warning: "border-amber-500/20 bg-amber-500/5",
  };

  return (
    <div className={cn("rounded-2xl border p-4", toneStyles[tone])}>
      <div className="flex items-center justify-between gap-3">
        <p className="font-medium text-sm">{label}</p>
        <Badge variant="outline" className="bg-background/70">
          {values.length}
        </Badge>
      </div>
      {values.length ? (
        <div className="mt-3 flex flex-wrap gap-2">
          {values.map((value) => (
            <Badge
              key={value}
              variant="outline"
              className="bg-background/80 font-mono shadow-sm"
            >
              {value}
            </Badge>
          ))}
        </div>
      ) : (
        <p className="mt-2 text-muted-foreground text-sm">{emptyText}</p>
      )}
    </div>
  );
}

function initials(first: string, last: string) {
  return `${first?.[0] ?? ""}${last?.[0] ?? ""}`.toUpperCase() || "?";
}
