'use client'

import PageTitle from "@/components/ui/PageTitle";
import {useFetchUsers} from "@/hooks/useFetchUsers";
import Spinner from "@/components/Spinner";
import useRoutes from "@/hooks/useRoutes";
import Link from "next/link";
import {PencilIcon, PlusIcon, TrashIcon} from "@heroicons/react/24/solid";
import React from "react";
import {deleteUser} from "@/utils/api/usersApi";
import {UserType} from "@/types/UserType";
import Card from "@/components/layout/Card";
import OutlineLinkButton from "@/components/ui/Buttons/OutlineLinkButton";

const UsersPage = () => {
    const { users, isLoading } = useFetchUsers();
    const routes = useRoutes();

    const handleDelete = (user: UserType) => {
        deleteUser(user)
            .then(() => window.location.reload())
    }

    if (isLoading) {
        return <Spinner />;
    }

    const usersList = () => {
        return users.map((user) => (
            <Card key={user.id}>
                <div className="flex-grow text-xl font-bold pt-1">
                    {user.name}
                </div>
                <div className="flex-none flex gap-2">
                    <div className="flex-none w-8">
                        <Link href={routes.user.edit(user)}>
                            <div className="border border-foreground p-2 rounded">
                                <PencilIcon width="14"/>
                            </div>
                        </Link>
                    </div>
                    <div className="flex-none w-8">
                        <Link href="#" onClick={() => handleDelete(user)}>
                            <div className="border border-red-500 p-2 rounded">
                                <TrashIcon width="14" className="text-red-500"/>
                            </div>
                        </Link>
                    </div>
                </div>
            </Card>
        ))
    };

    return (
        <div className="w-full">
            <div className="flex w-full">
                <div className="w-1/2 flex-none pt-2">
                    <PageTitle>Users</PageTitle>
                </div>

                <div className="flex-grow flex justify-end">
                    <OutlineLinkButton href={routes.user.create()} variant="primary">
                        <PlusIcon className="w-4 h-4 mt-1 mr-1"/>
                        <p>Add User</p>
                    </OutlineLinkButton>
                </div>
            </div>

            {
                users && users.length > 0
                    ? usersList()
                    : <div>No users</div>
            }
        </div>
    );
}

export default UsersPage;