"use client";

import * as React from "react";
import Link from "next/link";
import {
  EllipsisVertical,
  ExternalLink,
  KeyRound,
  Pencil,
  ShieldCheck,
  ShieldOff,
  Trash2,
} from "lucide-react";
import { Avatar } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ActionButton } from "@/components/ui/action-button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { UserFormDialog } from "@/components/admin/user-form-dialog";
import { ResetPasswordDialog } from "@/components/admin/reset-password-dialog";
import { deleteUserAction, setUserStatusAction } from "@/actions/admin";
import { formatRelativeTime } from "@/lib/format";
import { ACCOUNT_STATUS_BADGE, ROLE_BADGE } from "@/lib/labels";
import type { AdminUserRow } from "@/lib/queries/admin";

/**
 * User directory table with per-row administration controls.
 *
 * Destructive and self-affecting actions are guarded twice: the client hides
 * them for the signed-in administrator's own row, and the server action rejects
 * them regardless of what the client sends.
 *
 * Suspend/activate and delete are rendered outside the dropdown because a
 * confirmation dialog mounted inside a dropdown's portal would be unmounted the
 * moment the menu closes.
 */
export function UserTable({
  rows,
  currentUserId,
}: {
  rows: AdminUserRow[];
  currentUserId: string;
}) {
  const [editing, setEditing] = React.useState<AdminUserRow | null>(null);
  const [resetting, setResetting] = React.useState<AdminUserRow | null>(null);

  return (
    <>
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Pengguna</TableHead>
            <TableHead>Peran</TableHead>
            <TableHead>Status</TableHead>
            <TableHead className="text-right">Level / XP</TableHead>
            <TableHead>Terakhir Masuk</TableHead>
            <TableHead className="text-right">Aksi</TableHead>
          </TableRow>
        </TableHeader>

        <TableBody>
          {rows.map((user) => {
            const roleBadge = ROLE_BADGE[user.role];
            const statusBadge = ACCOUNT_STATUS_BADGE[user.status];
            const isSelf = user.id === currentUserId;

            return (
              <TableRow key={user.id}>
                <TableCell>
                  <div className="flex items-center gap-3">
                    <Avatar name={user.fullName} src={user.avatarUrl} size="sm" />
                    <div className="min-w-0">
                      <Link
                        href={`/dashboard/users/${user.id}`}
                        className="block truncate font-medium text-primary hover:text-brand-600 dark:hover:text-brand-400"
                      >
                        {user.fullName}
                        {isSelf ? (
                          <span className="ml-1.5 text-xs font-normal text-tertiary">(kamu)</span>
                        ) : null}
                      </Link>
                      <p className="truncate text-xs text-tertiary">
                        @{user.username}
                        {user.gradeLevel ? ` · Kelas ${user.gradeLevel}` : ""}
                      </p>
                    </div>
                  </div>
                </TableCell>

                <TableCell>
                  <Badge variant={roleBadge.variant}>{roleBadge.label}</Badge>
                </TableCell>

                <TableCell>
                  <Badge variant={statusBadge.variant}>{statusBadge.label}</Badge>
                </TableCell>

                <TableCell className="text-right tabular-nums">
                  <span className="font-medium text-primary">Lv {user.level}</span>
                  <span className="block text-xs text-tertiary">
                    {user.xp.toLocaleString("id-ID")} XP
                  </span>
                </TableCell>

                <TableCell className="whitespace-nowrap text-xs">
                  {user.lastLoginAt ? formatRelativeTime(user.lastLoginAt) : "Belum pernah"}
                </TableCell>

                <TableCell>
                  <div className="flex items-center justify-end gap-1">
                    {isSelf ? null : user.status === "ACTIVE" ? (
                      <ActionButton
                        action={setUserStatusAction}
                        fields={{ userId: user.id, status: "SUSPENDED" }}
                        label={<span className="sr-only">Tangguhkan akun {user.fullName}</span>}
                        icon={<ShieldOff className="size-3.5" />}
                        variant="ghost"
                        size="icon-sm"
                        confirm={`Akun "${user.fullName}" akan ditangguhkan dan seluruh sesinya diakhiri.`}
                        confirmTitle="Tangguhkan akun?"
                        confirmLabel="Tangguhkan"
                      />
                    ) : (
                      <ActionButton
                        action={setUserStatusAction}
                        fields={{ userId: user.id, status: "ACTIVE" }}
                        label={<span className="sr-only">Aktifkan akun {user.fullName}</span>}
                        icon={<ShieldCheck className="size-3.5" />}
                        variant="ghost"
                        size="icon-sm"
                      />
                    )}

                    {isSelf ? null : (
                      <ActionButton
                        action={deleteUserAction}
                        fields={{ userId: user.id }}
                        label={<span className="sr-only">Hapus akun {user.fullName}</span>}
                        icon={<Trash2 className="size-3.5" />}
                        variant="ghost"
                        size="icon-sm"
                        className="text-danger-600 hover:bg-danger-50 dark:text-danger-500 dark:hover:bg-danger-700/15"
                        confirm={`Akun "${user.fullName}" akan dihapus permanen. Pengguna yang memiliki kursus, kelas, tugas, atau proyek tidak dapat dihapus.`}
                        confirmTitle="Hapus pengguna?"
                        confirmLabel="Hapus Permanen"
                      />
                    )}

                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button
                          variant="ghost"
                          size="icon-sm"
                          aria-label={`Aksi lain untuk ${user.fullName}`}
                        >
                          <EllipsisVertical className="size-4" />
                        </Button>
                      </DropdownMenuTrigger>

                      <DropdownMenuContent>
                        <DropdownMenuLabel>Aksi</DropdownMenuLabel>

                        <DropdownMenuItem asChild>
                          <Link href={`/dashboard/users/${user.id}`}>
                            <ExternalLink />
                            Lihat Detail
                          </Link>
                        </DropdownMenuItem>

                        <DropdownMenuItem
                          onSelect={(event) => {
                            event.preventDefault();
                            setEditing(user);
                          }}
                        >
                          <Pencil />
                          Ubah Data
                        </DropdownMenuItem>

                        <DropdownMenuItem
                          onSelect={(event) => {
                            event.preventDefault();
                            setResetting(user);
                          }}
                        >
                          <KeyRound />
                          Reset Kata Sandi
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </div>
                </TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>

      {editing ? (
        <UserFormDialog
          mode="edit"
          open
          onOpenChange={(open) => {
            if (!open) setEditing(null);
          }}
          user={{
            id: editing.id,
            username: editing.username,
            fullName: editing.fullName,
            email: editing.email,
            role: editing.role,
            status: editing.status,
            school: editing.school,
            gradeLevel: editing.gradeLevel,
          }}
        />
      ) : null}

      {resetting ? (
        <ResetPasswordDialog
          userId={resetting.id}
          userName={resetting.fullName}
          open
          onOpenChange={(open) => {
            if (!open) setResetting(null);
          }}
        />
      ) : null}
    </>
  );
}
