import { ActionIcon, Badge, Box, Table, Tooltip } from "@mantine/core";
import { t } from "@/config/i18n";
import { IconEdit, IconX } from "@tabler/icons-react";
import { type User } from "@/services/resources/users";
import { useNavigate, useSearchParams } from "react-router";

export type UserRowProps = {
    user: User;
};

export default function UserRow({ user }: UserRowProps) {
    const [searchParams] = useSearchParams();
    const navigate = useNavigate();

    return (
        <Table.Tr key={user.id}>
            <Table.Td>{user.name}</Table.Td>
            <Table.Td>{user.email}</Table.Td>
            <Table.Td style={{ maxWidth: 200 }}>
                <Box
                    style={{
                        display: "flex",
                        gap: 4,
                    }}
                >
                    {user.roles.slice(0, 3).map((value) => (
                        <Badge key={value.id} size="xs">
                            {t(value.name, { capfirst: true })}
                        </Badge>
                    ))}
                    {user.roles.length > 3 && (
                        <Tooltip label={user.roles.slice(3).map((role) => `${role.name} `)}>
                            <Badge size="xs" variant="light">
                                +{user.roles.length - 3}
                            </Badge>
                        </Tooltip>
                    )}
                </Box>
            </Table.Td>
            <Table.Td>
                <Tooltip label={t("edit user", { capfirst: true })}>
                    <ActionIcon
                        size="sm"
                        mr="5"
                        onClick={(e) => {
                            e.stopPropagation();
                            navigate(
                                `/dashboard/users/${user.id}/edit${searchParams ? `?${searchParams.toString()}` : ""}`,
                            );
                        }}
                    >
                        <IconEdit />
                    </ActionIcon>
                </Tooltip>
                <Tooltip label={t("remove user", { capfirst: true })}>
                    <ActionIcon
                        color="red"
                        size="sm"
                        mr="5"
                        onClick={(e) => {
                            e.stopPropagation();
                            navigate(
                                `/dashboard/users/${user.id}/delete${searchParams ? `?${searchParams.toString()}` : ""}`,
                            );
                        }}
                    >
                        <IconX />
                    </ActionIcon>
                </Tooltip>
            </Table.Td>
        </Table.Tr>
    );
}
