// src/components/admin/user-detail.tsx — God-Mode user-detail action panels.
// Client component: renders the target's identity, org memberships and live
// sessions, plus the destructive action panels (suspend/ban, lift, edit email,
// force-verify, reset 2FA, revoke sessions, impersonate). Every mutation calls
// a 2FA-gated + audited server action; on success we refresh the RSC tree.
"use client";

import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useState, useTransition } from "react";
import { toast } from "sonner";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  banUserAction,
  type AdminUserDetail as Detail,
  forceVerifyEmailAction,
  impersonateUserAction,
  resetUserTwoFactorAction,
  revokeAllUserSessionsAction,
  revokeOneUserSessionAction,
  unbanUserAction,
  updateUserEmailAction,
} from "@/lib/admin/actions";

// Suspension presets → seconds (undefined = permanent ban).
const DURATIONS: Record<string, number | undefined> = {
  "1h": 3600,
  "24h": 86_400,
  "7d": 604_800,
  "30d": 2_592_000,
  permanent: undefined,
};

function fmt(d: Date | string): string {
  return new Date(d).toLocaleString();
}

export function AdminUserDetail({ detail }: { detail: Detail }) {
  const t = useTranslations("SuperAdmin");
  const router = useRouter();
  const [pending, startTransition] = useTransition();

  // Ban dialog state.
  const [banReason, setBanReason] = useState("");
  const [banDuration, setBanDuration] = useState("permanent");
  // Email dialog state.
  const [email, setEmail] = useState(detail.email);
  const [markVerified, setMarkVerified] = useState(false);

  // Run a mutation, surface errors as toasts, refresh on success.
  function run(action: () => Promise<void>, okMsg: string) {
    startTransition(async () => {
      try {
        await action();
        toast.success(okMsg);
        router.refresh();
      } catch (err) {
        toast.error(err instanceof Error ? err.message : t("actionError"));
      }
    });
  }

  return (
    <div className="space-y-6">
      {/* Identity header */}
      <div className="space-y-2 rounded-lg border p-4">
        <div className="flex flex-wrap items-center gap-2">
          <h1 className="font-semibold text-xl">{detail.name}</h1>
          <Badge variant={detail.role === "admin" ? "default" : "secondary"}>
            {detail.role === "admin" ? t("roleAdmin") : t("roleUser")}
          </Badge>
          {detail.banned ? (
            <Badge variant="destructive">{t("statusBanned")}</Badge>
          ) : (
            <Badge variant="outline">{t("statusActive")}</Badge>
          )}
          {detail.twoFactorEnabled ? (
            <Badge variant="outline">{t("badge2faOn")}</Badge>
          ) : null}
        </div>
        <div className="text-muted-foreground text-sm">
          <span>{detail.email}</span>{" "}
          {detail.emailVerified ? (
            <Badge variant="outline" className="ml-1">
              {t("badgeVerified")}
            </Badge>
          ) : (
            <Badge variant="secondary" className="ml-1">
              {t("badgeUnverified")}
            </Badge>
          )}
        </div>
        <dl className="grid grid-cols-2 gap-2 text-sm sm:grid-cols-3">
          <div>
            <dt className="text-muted-foreground text-xs">
              {t("detailUsername")}
            </dt>
            <dd>{detail.username ?? "—"}</dd>
          </div>
          <div>
            <dt className="text-muted-foreground text-xs">
              {t("detailCreatedAt")}
            </dt>
            <dd>{fmt(detail.createdAt)}</dd>
          </div>
          <div>
            <dt className="text-muted-foreground text-xs">{t("detailId")}</dt>
            <dd className="truncate font-mono text-xs">{detail.id}</dd>
          </div>
        </dl>
        {detail.banned ? (
          <p className="text-destructive text-xs">
            {t("banReasonLabel")}: {detail.banReason ?? "—"}
            {detail.banExpires
              ? ` · ${t("banExpiresLabel")}: ${fmt(detail.banExpires)}`
              : ` · ${t("banPermanent")}`}
          </p>
        ) : null}
      </div>

      {/* Org memberships */}
      <div className="space-y-2 rounded-lg border p-4">
        <h2 className="font-medium text-sm">{t("membershipsTitle")}</h2>
        {detail.memberships.length === 0 ? (
          <p className="text-muted-foreground text-sm">
            {t("membershipsEmpty")}
          </p>
        ) : (
          <ul className="space-y-1 text-sm">
            {detail.memberships.map((m) => (
              <li
                key={m.organizationId}
                className="flex items-center justify-between"
              >
                <span>{m.organizationName}</span>
                <Badge variant="secondary">{m.role}</Badge>
              </li>
            ))}
          </ul>
        )}
      </div>

      {/* Action panels */}
      <div className="space-y-3 rounded-lg border p-4">
        <h2 className="font-medium text-sm">{t("actionsTitle")}</h2>
        <div className="flex flex-wrap gap-2">
          {/* Suspend / ban */}
          {detail.banned ? (
            <Button
              variant="outline"
              size="sm"
              disabled={pending}
              onClick={() =>
                run(() => unbanUserAction(detail.id), t("toastBanLifted"))
              }
            >
              {t("liftBan")}
            </Button>
          ) : (
            <Dialog>
              <DialogTrigger asChild>
                <Button variant="destructive" size="sm" disabled={pending}>
                  {t("suspendBan")}
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>{t("suspendDialogTitle")}</DialogTitle>
                  <DialogDescription>
                    {t("suspendDialogBody")}
                  </DialogDescription>
                </DialogHeader>
                <div className="space-y-3">
                  <div className="space-y-1">
                    <Label htmlFor="ban-reason">{t("reasonLabel")}</Label>
                    <Input
                      id="ban-reason"
                      value={banReason}
                      onChange={(e) => setBanReason(e.target.value)}
                      placeholder={t("reasonPlaceholder")}
                    />
                  </div>
                  <div className="space-y-1">
                    <Label htmlFor="ban-duration">{t("durationLabel")}</Label>
                    <Select value={banDuration} onValueChange={setBanDuration}>
                      <SelectTrigger id="ban-duration" className="w-full">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent position="popper">
                        <SelectItem value="1h">{t("duration1h")}</SelectItem>
                        <SelectItem value="24h">{t("duration24h")}</SelectItem>
                        <SelectItem value="7d">{t("duration7d")}</SelectItem>
                        <SelectItem value="30d">{t("duration30d")}</SelectItem>
                        <SelectItem value="permanent">
                          {t("durationPermanent")}
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <DialogFooter>
                  <DialogClose asChild>
                    <Button variant="outline" size="sm">
                      {t("cancel")}
                    </Button>
                  </DialogClose>
                  <DialogClose asChild>
                    <Button
                      variant="destructive"
                      size="sm"
                      disabled={pending}
                      onClick={() =>
                        run(
                          () =>
                            banUserAction(detail.id, {
                              reason: banReason.trim() || undefined,
                              durationSeconds: DURATIONS[banDuration],
                            }),
                          t("toastBanned"),
                        )
                      }
                    >
                      {t("confirmSuspend")}
                    </Button>
                  </DialogClose>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          )}

          {/* Edit email */}
          <Dialog>
            <DialogTrigger asChild>
              <Button variant="outline" size="sm" disabled={pending}>
                {t("editEmail")}
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>{t("editEmailTitle")}</DialogTitle>
                <DialogDescription>{t("editEmailBody")}</DialogDescription>
              </DialogHeader>
              <div className="space-y-3">
                <div className="space-y-1">
                  <Label htmlFor="new-email">{t("emailLabel")}</Label>
                  <Input
                    id="new-email"
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </div>
                <div className="flex items-center gap-2">
                  <Checkbox
                    id="mark-verified"
                    checked={markVerified}
                    onCheckedChange={(c) => setMarkVerified(c === true)}
                  />
                  <Label htmlFor="mark-verified">{t("markVerified")}</Label>
                </div>
              </div>
              <DialogFooter>
                <DialogClose asChild>
                  <Button variant="outline" size="sm">
                    {t("cancel")}
                  </Button>
                </DialogClose>
                <DialogClose asChild>
                  <Button
                    size="sm"
                    disabled={pending}
                    onClick={() =>
                      run(
                        () =>
                          updateUserEmailAction(detail.id, {
                            email: email.trim(),
                            markVerified,
                          }),
                        t("toastEmailUpdated"),
                      )
                    }
                  >
                    {t("save")}
                  </Button>
                </DialogClose>
              </DialogFooter>
            </DialogContent>
          </Dialog>

          {/* Force-verify email */}
          {detail.emailVerified ? null : (
            <Button
              variant="outline"
              size="sm"
              disabled={pending}
              onClick={() =>
                run(
                  () => forceVerifyEmailAction(detail.id),
                  t("toastForceVerified"),
                )
              }
            >
              {t("forceVerify")}
            </Button>
          )}

          {/* Reset 2FA */}
          {detail.twoFactorEnabled ? (
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button variant="outline" size="sm" disabled={pending}>
                  {t("reset2fa")}
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>{t("reset2faTitle")}</AlertDialogTitle>
                  <AlertDialogDescription>
                    {t("reset2faBody")}
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>{t("cancel")}</AlertDialogCancel>
                  <AlertDialogAction
                    onClick={() =>
                      run(
                        () => resetUserTwoFactorAction(detail.id),
                        t("toast2faReset"),
                      )
                    }
                  >
                    {t("confirm")}
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          ) : null}

          {/* Revoke all sessions */}
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button variant="outline" size="sm" disabled={pending}>
                {t("revokeAllSessions")}
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>{t("revokeAllTitle")}</AlertDialogTitle>
                <AlertDialogDescription>
                  {t("revokeAllBody")}
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>{t("cancel")}</AlertDialogCancel>
                <AlertDialogAction
                  onClick={() =>
                    run(
                      () => revokeAllUserSessionsAction(detail.id),
                      t("toastSessionsRevoked"),
                    )
                  }
                >
                  {t("confirm")}
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>

          {/* Impersonate (hidden for admins/super-admins). Redirects on success. */}
          {detail.impersonable ? (
            <Button
              variant="outline"
              size="sm"
              disabled={pending}
              onClick={() =>
                startTransition(() => impersonateUserAction(detail.id))
              }
            >
              {t("impersonate")}
            </Button>
          ) : null}
        </div>
      </div>

      {/* Live sessions */}
      <div className="space-y-2 rounded-lg border p-4">
        <h2 className="font-medium text-sm">{t("sessionsTitle")}</h2>
        <div className="rounded-lg border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t("sessionDevice")}</TableHead>
                <TableHead>{t("sessionIp")}</TableHead>
                <TableHead>{t("sessionCreated")}</TableHead>
                <TableHead>{t("sessionExpires")}</TableHead>
                <TableHead className="text-right">
                  {t("columnActions")}
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {detail.sessions.length === 0 ? (
                <TableRow>
                  <TableCell
                    colSpan={5}
                    className="py-8 text-center text-muted-foreground text-sm"
                  >
                    {t("sessionsEmpty")}
                  </TableCell>
                </TableRow>
              ) : (
                detail.sessions.map((s) => (
                  <TableRow key={s.id}>
                    <TableCell className="max-w-48 truncate text-xs">
                      {s.userAgent ?? "—"}
                      {s.impersonated ? (
                        <Badge variant="secondary" className="ml-1">
                          {t("sessionImpersonated")}
                        </Badge>
                      ) : null}
                    </TableCell>
                    <TableCell className="text-xs">
                      {s.ipAddress ?? "—"}
                    </TableCell>
                    <TableCell className="text-xs">
                      {fmt(s.createdAt)}
                    </TableCell>
                    <TableCell className="text-xs">
                      {fmt(s.expiresAt)}
                    </TableCell>
                    <TableCell className="text-right">
                      <Button
                        variant="ghost"
                        size="sm"
                        disabled={pending}
                        onClick={() =>
                          run(
                            () => revokeOneUserSessionAction(detail.id, s.id),
                            t("toastSessionRevoked"),
                          )
                        }
                      >
                        {t("revoke")}
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </div>
    </div>
  );
}
