import {useQuery} from "@tanstack/react-query";
import {InventoryItem} from "./types";
import {Flex, Table} from '@mantine/core';
import BarkButton from "../../common/components/BarkButton.tsx";
import {Link} from "react-router";

function InventoryList() {

    const { isPending, error, data, isFetching } = useQuery({
        queryKey: ['inventory'],
        queryFn: async (): Promise<InventoryItem[]> => {
            const response = await fetch(
                import.meta.env.VITE_API_URL + '/inventory',
            )

            if (!response.ok) throw new Error('Failed to fetch inventory ' + response.statusText)

            return await response.json()
        },
    });

    if (isPending) return 'Loading...'

    if (error) return 'An error has occurred: ' + error.message


    return (
        <>
            <Flex
                mih={50}
                gap="xl"
                justify="center"
                align="center"
                direction="row"
                wrap="wrap"
            >
                <p>
                    ARFF ARFF BARK BARK
                </p>
                <BarkButton>Add Item</BarkButton>
            </Flex>


            <div>{isFetching ? 'Updating...' : ''}</div>

            <Table striped>
            <Table.Thead>
                <Table.Tr>
                    <Table.Th c="red">ID</Table.Th>
                    <Table.Th c="red">Brand</Table.Th>
                    <Table.Th c="red">Item</Table.Th>
                    <Table.Th c="red">Status</Table.Th>
                    <Table.Th c="red">Details</Table.Th>
                </Table.Tr>
                </Table.Thead>
                <Table.Tbody>
                {data.map((data) => (
                    <Table.Tr key={data.id}>
                        <Table.Td>{data.id}</Table.Td>
                        <Table.Td>{data.brand}</Table.Td>
                        <Table.Td>{data.name}</Table.Td>
                        <Table.Td>{data.statusId}</Table.Td>
                        <Table.Td>
                            <Link to={`/itemDetail/${data.id}`}>Details</Link>
                        </Table.Td>
                    </Table.Tr>
                ))}
                </Table.Tbody>
            </Table>
        </>
    )
}
export default InventoryList;