import React, { useMemo } from "react";
import AppLayout from "@/layouts/app-layout";
import { Card, Container, Group, Button, Title, ActionIcon } from "@mantine/core";
import { MantineReactTable } from "mantine-react-table";
import { IconEdit, IconPlus } from "@tabler/icons-react";
import { Link } from "@inertiajs/react";
import { User } from "@/types";
import type { MRT_Row } from "mantine-react-table";

interface Props {
    users: User[];
}

export default function Page({ users }: Props) {
    const data = users ?? [];

    const columns = useMemo(
        () => [
            {
                accessorKey: "name",
                header: "Name",
            },
            {
                accessorKey: "email",
                header: "Email",
            },
            {
                id: "roles",
                header: "Roles",
                accessorFn: (row: User) =>
                    row.roles?.map((role) => role.name).join(", ") ?? "—",
            },
            {
                id: "manager",
                header: "Reports To",
                accessorFn: (row: User) => row.manager?.name ?? "—",
            },
        ],
        [],
    );

    const renderRowActions = ({ row }: { row: MRT_Row<User> }) => (
        <ActionIcon
            component={Link}
            href={route("management.users.edit", { id: row.original.id })}
            color="blue"
            variant="light"
        >
            <IconEdit size={18} />
        </ActionIcon>
    );

    return (
        <AppLayout>
            <Container size="xl" px="xs">
                <Group position="apart" mb="md">
                    <Title order={2}>Users</Title>
                    <Button
                        component={Link}
                        href={route("management.users.create")}
                        leftIcon={<IconPlus size={16} />}
                    >
                        New User
                    </Button>
                </Group>

                <Card>
                    <MantineReactTable
                        columns={columns}
                        data={data}
                        enablePagination
                        rowCount={data.length}
                        initialState={{ pagination: { pageIndex: 0, pageSize: 10 } }}
                        renderRowActions={renderRowActions}
                        enableRowActions
                        columnPinning={{ right: ['mrt-row-actions'] }}
                    />
                </Card>
            </Container>
        </AppLayout>
    );
}
