"use client";

import { type ReactNode } from "react";
import type { UserViewModel } from "@/types/view-models";
import { Badge, Button, Table, TableRow, TableCell } from "./ui";
import { t } from "@/lib/i18n";

interface UserManagementTableProps {
  users: UserViewModel[];
  onEdit: (user: UserViewModel) => void;
  onToggleStatus: (user: UserViewModel) => void;
  onCreate: () => void;
}

export function UserManagementTable({
  users,
  onEdit,
  onToggleStatus,
  onCreate,
}: UserManagementTableProps): ReactNode {
  return (
    <div>
      <div className="flex justify-end mb-4">
        <Button variant="primary" onClick={onCreate}>
          {t("admin.users.new")}
        </Button>
      </div>
      <Table
        headers={[
          "邮箱",
          "姓名",
          "角色",
          "状态",
          "数据范围",
          "学校",
          "最后登录",
          "操作",
        ]}
      >
        {users.map((user) => (
          <TableRow key={user.id}>
            <TableCell>{user.email}</TableCell>
            <TableCell>{user.name}</TableCell>
            <TableCell>
              {user.roles.map((r) => r.name).join(", ") || "—"}
            </TableCell>
            <TableCell>
              <Badge status={user.status} />
            </TableCell>
            <TableCell>{user.dataScope}</TableCell>
            <TableCell>{user.schoolName ?? "—"}</TableCell>
            <TableCell>
              {user.lastLoginAt
                ? new Date(user.lastLoginAt).toLocaleDateString("zh-CN")
                : "—"}
            </TableCell>
            <TableCell>
              <div className="flex gap-2">
                <Button variant="ghost" onClick={() => onEdit(user)}>
                  {t("admin.common.edit")}
                </Button>
                <Button variant="ghost" onClick={() => onToggleStatus(user)}>
                  {t("admin.users.toggleStatus")}
                </Button>
              </div>
            </TableCell>
          </TableRow>
        ))}
      </Table>
    </div>
  );
}
